I am doing problem five in Project Euler: "2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?"
I have constructed the following code which finds the correct value 2520 when using 1 - 10 as divisors but code seems to be going on forever when using 1 - 20.
Again I don't want the code just a pointer or two on where I am going wrong.
while end == False:
divisors = [x for x in range(1,21)] # get divisors
allDivisions = zip(n % i for i in divisors) # get values for n % all integers in divisors
check = all(item == 0 for item in allDivisions ) # check if all values of n % i are equal to zero
if check: # if all values are equal to zero return n
end = True
else: # else increase n by 1
values = [value for value in values]
n = max(values)
m = n
while any( n % value for value in values ):
print reduce(lcm, range(1,21))
If a problem is hard, trying solving a simpler version. Here, how to calculate the lowest common multiple of two numbers. If you've read any number theory book (or think about prime factors), you can do that using the greatest common divisor function (as implemented by the Euclidean algorithm).
from fractions import gcd def lcm(a,b): "Calculate the lowest common multiple of two integers a and b" return a*b//gcd(a,b)
lcm(a,b,c) ≡ lcm(lcm(a,b),c) it's simple to solve your problem with Python's
>>> from functools import reduce >>> reduce(lcm, range(1,10+1)) 2520 >>> reduce(lcm, range(1,20+1)) 232792560