Command Palette

Search for a command to run...

Module 39

Math for Coding Interviews

GCD and LCM, primes with a sieve, modular arithmetic, fast exponentiation, modular inverses, nCr, and safe digit manipulation.

Advanced 3 lessons 9 problems ~40 min of lessons

A handful of number-theory tools appear again and again: Euclid's GCD, the sieve of Eratosthenes, "return the answer modulo 10⁹ + 7", raising numbers to huge powers, dividing under a modulus, and counting arrangements with factorials.

This module explains each tool from first principles, shows the overflow traps in Java, and practises them on problems where the math replaces a loop or makes an impossible count possible.

Best after: Big-O and Complexity

Where this shows up in real systems

Part 1

Learn the ideas

Part 2

Solve the problems

Work through them in order. Each one shows the pattern it teaches.

  1. GCD applied to string lengths, after a commutativity check.

  2. The sieve of Eratosthenes.

  3. Bézout's identity: reachable amounts are multiples of gcd(x, y) up to x + y.

  4. Base 26 with digits 1–26.

  5. Count factors of 5 instead of computing n!.

  6. Digit extraction with an overflow check before each step.

  7. Fast modular exponentiation for counts with huge n.

  8. An exponent given as a digit array: a^(10k + d) = (a^k)^10 × a^d.

  9. Multinomial coefficients under a modulus with factorials and inverse factorials.