Algorithms · Visualized

Number Theory: LCM

Number Theory

Divisibility, primes, hashes and modular arithmetic — the math underneath algorithms.

The least common multiple of two numbers is the smallest number divisible by both. Time: O(log(min(a,b))) — dominated by the GCD computation average, O(log(min(a,b))) worst; space: O(1).

Big-O: GCD O(log min(a,b)); sieve O(n log log n).

LCM (Least Common Multiple)

Number Theory

The least common multiple of two numbers is the smallest number divisible by both. Rather than searching multiples one by one, it can be computed directly from the GCD using the relationship: LCM(a, b) = (a × b) / GCD(a, b).

How LCM Works

  1. Compute the GCD of the two numbers using the Euclidean algorithm.
  2. Multiply the two original numbers together.
  3. Divide that product by the GCD computed in step 1.
  4. The result is the least common multiple.
  5. (To avoid overflow with large numbers, it's common to divide by the GCD first, then multiply: (a / GCD) × b.)

LCM Worked Example

Input: {a: 4, b: 6}

GCD(4,6) = 2. LCM = (4 × 6) / 2 = 24 / 2 = 12. Check: 12 is divisible by both 4 and 6, and it's the smallest such number.

Number Theory: LCMO(log min(a,b))
lcm(a,b) = a × b / gcd(a,b).
4
0
6
1
Step 1 / 5
Default Current / Compare Swap / Write Settled Active / Path Pivot / Reject Locked (hollow) Target
LCM(4, 6): first compute GCD, then lcm = a × b / gcd.
Python · Number Theory in Code
def lcm(a, b):
    return a * b // gcd(a, b)

Behind the Scenes Execution

Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.

LCM Time & Space Complexity

BestO(1)
AverageO(log(min(a,b))) — dominated by the GCD computation
WorstO(log(min(a,b)))
SpaceO(1)

When to Use LCM

  • Scheduling problems: finding when repeating events next align (e.g. two buses on different cycles arriving together).
  • Adding fractions with different denominators requires finding their LCM as a common denominator.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Keep the momentum going

Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.