To solve this problem, we need to find the smallest positive number that is evenly divisible by all numbers from 1 to 20. This number is known as the Least Common Multiple (LCM) of the range 1 to 20.
Approach
The LCM of a set of numbers can be computed iteratively using the formula:
*LCM(a, b) = (a b) // GCD(a, b)**
where GCD (Greatest Common Divr) is calculated using the Euclidean algorithm.
Steps:
- Start with an initial LCM value of 1.
- For each number from 1 to 20, update the LCM by computing the LCM of the current result and the next number.
- Use the GCD to efficiently compute the LCM for each pair of numbers.
Solution Code
import math
def smallest_divisible_by_range(max_num):
lcm = 1
for num in range(1, max_num + 1):
lcm = lcm * num // math.gcd(lcm, num)
return lcm
print(smallest_divisible_by_range(20))
Explanation
- GCD Calculation: The Euclidean algorithm (implemented in
math.gcd) finds the largest number that divides both input numbers without remainder. - Iterative LCM: For each number from 1 to 20, we compute the LCM of the current result and the number. This cumulative LCM gives the smallest number divisible by all numbers up to 20.
The result of the code is 232792560, which is the smallest number divisible by all numbers from 1 to 20.
Answer: 232792560


作者声明:本文包含人工智能生成内容。