Smallest Integer Divisible by All in Range
Math & Bit ManipulationAuto-graded · 19 test casesLast updated
Tests understanding of LCM computation via repeated GCD to find the least positive integer divisible by every integer in a given range.
Smallest Integer Divisible by All in Range
Given two integers lo and hi (with lo <= hi), return the least common multiple (LCM) of all integers from lo to hi, inclusive.
In other words, find the smallest positive integer that is divisible by every integer in the range [lo, hi].
If lo == hi, the answer is simply lo itself.
Note: The result can be very large. Return it as a Python int (arbitrary precision is fine).
Constraints
1 <= lo <= hi <= 20- The answer always fits in a standard Python
int.
Examples
Example 1
Input: range_lcm(1, 5)
Output: 60
Example 2
Input: range_lcm(3, 3)
Output: 3
Example 3
Input: range_lcm(2, 10)
Output: 2520
Hints
Hint 1
The LCM of a collection of numbers can be computed incrementally: lcm(a, b, c) = lcm(lcm(a, b), c).
Hint 2
Recall that lcm(a, b) = a * b // gcd(a, b). Python's math module provides math.gcd.
Hint 3
Start with result = lo, then loop from lo+1 through hi, updating result = lcm(result, next_value) at each step.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key Insight
The LCM of a set of numbers can be computed incrementally using the identity:
lcm(a, b) = a * b // gcd(a, b)
We start with result = lo and fold each subsequent integer n in [lo+1, hi] into the running result by computing lcm(result, n).
This works because LCM is associative and commutative:
lcm(a, b, c) = lcm(lcm(a, b), c)
Why It Is Correct
- For a single element (
lo == hi), the loop body never executes and we returnlodirectly. - Each update
result = result * n // gcd(result, n)maintains the invariant thatresultis divisible by every integer seen so far while staying as small as possible. - The
//(integer floor division) is exact here becausegcd(result, n)always dividesresult * n.
Complexity
| Complexity | |
|---|---|
| Time | O((hi − lo) · log(hi)) — one GCD call per step, each O(log hi) |
| Space | O(1) — only a single running integer is kept |
For the given constraints (hi ≤ 20), this is essentially instantaneous.
Reference Solution
from math import gcd
def range_lcm(lo: int, hi: int) -> int:
result = lo
for n in range(lo + 1, hi + 1):
result = result * n // gcd(result, n)
return result