KatInterview

Smallest Integer Divisible by All in Range

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

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