Note - if you want to solve project Euler yourself, don't cheat and peek at the rest of the post. Take this as a warning - the answer is at the end.
The problem?
Immediately I realized that I would have to know the LCM of the number pairs between 1 and 20. LCM is a commonly implemented feature in software. The quickest method I knew of off the top of my head: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 number that is evenly divisible by all of the numbers from 1 to 20?
def lcm(a, b): return a*b / gcd(a, b)
Where I used the following for GCD
def gcd(a, b):if b == 0: return areturn gcd(b, a % b)
The rest fell into place:
data = range(1, 20 + 1)
tmp = []
while len(data) > 1:
print data
print tmp
for i in range(0, len(data), 2):
if len(data)%1 == 0 and i is not 5:
tmp.append(lcm(data[i], data[i-1]))
else:
tmp.append(lcm(data[i+1], data[i]))
data = tmp
tmp = []
print data
The returned answer? 5,342,931,457,063,200! Sheesh!
No comments:
Post a Comment