patternpythonMinor
Project Euler Problem 5
Viewed 0 times
problemprojecteuler
Problem
I wrote up a small script to calculate the answer to Project Euler Problem 5:
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'm wondering if this algorithm can be improved or made more efficient:
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'm wondering if this algorithm can be improved or made more efficient:
def divisible_by(num, den_set):
if not den_set: return True
elif not num % den_set.pop():
return divisible_by(num, den_set)
else: return False
def smallest(den_count):
i = 1
den_set = list(range(1, den_count))
while not divisible_by(i, den_set):
den_set = list(range(1, den_count))
i += 1
return i
print smallest(20)Solution
The smallest number that can be divided by a set of numbers without any remainder is also known as the least common multiple, which can be calculated directly using the greatest common divisor (gcd).
The least common multiple of a, b:
The least common multiple of a, b, c:
You could generalize this to more numbers.
The least common multiple of a, b:
lcm(a, b) = a * b / gcd(a, b)The least common multiple of a, b, c:
lcm(a, b, c) = lcm(a, lcm(b, c))You could generalize this to more numbers.
Code Snippets
lcm(a, b) = a * b / gcd(a, b)lcm(a, b, c) = lcm(a, lcm(b, c))Context
StackExchange Code Review Q#95936, answer score: 4
Revisions (0)
No revisions yet.