KatInterview

Smallest Integer Divisible by All Segment Lengths

Math & Bit ManipulationAuto-graded · 19 test cases
MediumAuto-gradedMath & Bit Manipulationmathnumber-theorygcd-lcm

Last 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:

  • T is 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 ≤ 500
  • hi - 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.