Your code has a significant logical flaw; when the for
loop ends (after 20 loops), the current value of x
is printed, without checking whether it is divisible by the appropriate numbers. You don't restart the for
loop from 1 each time you increment x
.
You need an outer loop to run until an appropriate x
is found; a while
loop, as we don't know how long it will run for. To minimally fix your code:
def even_divisible():
x=1
while True: # outer loop
for i in range(1,21): # inner loop
if x % i != 0:
x+=1
break # break for loop
else: # for loop ran to end without break
break # break while loop
print x
You can simplify with any
or all
for the inner loop. There are a few mathematical simplifications, too; given that we know that x % 20 == 0
, we only need look at multiples of 20, and since all integers are integer multiples of 1 we can start from 2:
def evenly_divisible(n):
x = n
while True: # outer loop over multiples of n
if all(x % i == 0 for i in range(2, n+1)): # inner loop over 2-n
return x
x += n