def ProjectEulerFive (m = 20):
a = m
start = 2
while (m % start) == 0:
start += 1
b = start
while b < m:
if ( a % b) != 0:
a += m
b = start
continueelse:
b += 1
return a
import sys
if (len(sys.argv)) > 2:
print "error: this function takes a max of 1 argument"
elif (len(sys.argv)) == 2:
print ProjectEulerFive(int(sys.argv[1]))
else:
print ProjectEulerFive();
And then I google it to see some other answers. Hadn't thought of using prime factorization trick. But Anyways, I came across this supposedly optimized solution on stackoverflow.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
check_list = [11, 13, 14, 16, 17, 18, 19, 20]
def find_solution(step):
for num in xrange(step, 999999999, step):
if all(num % n == 0 for n in check_list):
return num
return None
if __name__ == '__main__':
solution = find_solution(20)
if solution is None:
print "No answer found"else:
print "found an answer:", solution
But I found that my solution runs about 4 times faster. So I'm wondering why my code is so much faster? My program even unnecessarily checks for divisibility by 3, 4, 5, 6, 7, 8, 9, 10, and 12.
My guess: all(num % n == 0 for n in check_list) creates an object, which requires memory allocation. This by itself could seriously slow down an otherwise speedy algorithm.