Smallest Integer Divisible by All Segment Lengths
Math & Bit ManipulationAuto-graded · 19 test casesLast updated
Tests the ability to apply LCM iteratively and use GCD to reduce it, while reasoning about arithmetic progressions and large-number arithmetic.
Fence Plank Scheduler
A carpenter is building a fence. She has planks of every integer length from lo to hi (inclusive). She wants to find the smallest positive integer T such that:
Tis divisible by every integer in the range[lo, hi].
In other words, compute LCM(lo, lo+1, lo+2, …, hi).
Because the answer can be astronomically large, return it modulo 10^9 + 7.
Important: The modular result must be the true LCM reduced mod
10^9 + 7. You are computing the exact LCM and then reducing — not taking LCM of modular values.
Constraints
1 ≤ lo ≤ hi ≤ 500hi - lo ≤ 300- The range always contains at least one integer (
lo ≤ hi).
Examples
Example 1
Input: fence_lcm(1, 5)
Output: 60
Example 2
Input: fence_lcm(3, 3)
Output: 3
Example 3
Input: fence_lcm(4, 8)
Output: 840
Hints
Hint 1
LCM of two numbers a and b equals a * b // gcd(a, b). You can chain this: LCM(a,b,c) = LCM(LCM(a,b),c).
Hint 2
Python integers have arbitrary precision, so compute the exact LCM first (without any modulo), then reduce the final result modulo 10^9+7 at the very end.
Hint 3
As you iterate from lo to hi, notice that if a number is already a divisor of the running LCM you've built so far, it contributes nothing new — gcd handles this automatically.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key Insight
The least common multiple of a collection of integers can be computed iteratively using the identity:
LCM(a, b) = a * b / GCD(a, b)
So LCM(lo, lo+1, ..., hi) = LCM(LCM(lo, lo+1, ..., hi-1), hi).
Why It Works
At each step, LCM(current, n) absorbs exactly the "new prime power content" that n contributes beyond what current already covers. The GCD captures shared factors precisely, so the division is always exact (no remainder) and keeps the running value as the true LCM.
Important: Modulo at the End
The LCM of a range like [1, 300] is an astronomically large number. We must maintain the exact integer throughout the loop (Python supports arbitrary-precision integers natively), and only reduce modulo 10^9 + 7 once at the very end. Taking modulo inside the loop would corrupt the GCD computations.
Complexity
- Time: O((hi − lo) · log(hi)) — one GCD per step, each GCD costs O(log hi).
- Space: O(1) extra (Python big integers grow as needed, but the running LCM is a single value).
Reference Solution
from math import gcd
def fence_lcm(lo: int, hi: int) -> int:
MOD = 10**9 + 7
result = lo
for n in range(lo + 1, hi + 1):
result = result * n // gcd(result, n)
return result % MOD
Verification on Sample Cases
lo | hi | Exact LCM | mod 10^9+7 |
|---|---|---|---|
| 1 | 5 | 60 | 60 |
| 3 | 3 | 3 | 3 |
| 4 | 8 | 840 | 840 |