Fangir
Fangir

Reputation: 151

Python: Print all numbers in range divisible by x and y

I'm trying to print all numbers in range 1-100 that are divisible by x and y (ie. 2 nad 3). For now i have

for x in range(0, 101):
    if x % (2 and 3) == 0: print("2, 3: ", x)
    elif x % 2 == 0: print("2: ", x)
    elif x % 3 == 0: print("3: ", x)

But it is not accurate, any suggestions?

Upvotes: 0

Views: 3469

Answers (4)

Philipp Lange
Philipp Lange

Reputation: 871

If you have a number that hast to be dividable by number x and number y you can look at it like: If some rest is left after a division with divisor x or divisor y, the currently considered number toDivide is not the number you are looking for, because you want numbers where neither of the devisions results in a rest.

x = 2
y = 3
for toDivide in range(1, 101):
    # can't divide by x and y
    if toDivide%x and toDivide%y:
        continue
    print((str(x)+", "+str(y) if not toDivide%x and not toDivide%y else (str(x) if not toDivide%x else str(y)))+":"+str(toDivide))

edit: found and resolved the code-error

Upvotes: -1

Vinícius Figueiredo
Vinícius Figueiredo

Reputation: 6518

(2 and 3) evaluates to 3, that's why you never see the condition elif x % 3 == 0 being executed, notice there's no print("3: ", x) in the output of your code, because it'd already fallen into the condition if x % (2 and 3) == 0.

You should be better using if ((x % 2) == 0 and (x % 3) == 0) : print("2, 3: ", x) on that line.

Upvotes: 4

Yonas Kassa
Yonas Kassa

Reputation: 3710

In if x % (2 and 3) == 0 the value of (2 and 3) is evaluated first, you should first check divisibility by 2 then by 3. i.e.

if (x % 2) and (x % 3)

the two expressions in brackets return booleans that you finally evaluate using and.

corrected:

for x in range(0, 101):
    if (x % 2) and (x % 3): 
        print("2, 3: ", x)
    elif x % 2 == 0: 
        print("2: ", x)
    elif x % 3 == 0: 
        print("3: ", x)

Upvotes: -2

lbrindze
lbrindze

Reputation: 78

The reason it is not accurate is by writing x % (2 and 3) python is interpreting (2 and 3).(https://docs.python.org/2/reference/expressions.html)

in python (2 and 3) would return 3 because both values are "truthy" and the AND comparison operator in python will return the last value when both items are True.

As per Rajesh Kumar's suggestion you could do if x % 6 == 0: # ... or if x % 2 == 0 and x % 3 == 0: # More verbose...

Upvotes: 3

Related Questions