Builds onBig-O and complexity
01The idea
A few pieces of number theory come up again and again. Each one replaces a slow loop with a short formula or a fast algorithm.
The greatest common divisor, gcd, is the largest number that divides both a and b. Euclid's algorithm finds it with one rule: gcd(x, y) = gcd(y, x % y), and gcd(x, 0) = x. Any number that divides x and y also divides the remainder x % y, so the pair shrinks without losing the answer. The numbers at least halve every two steps, so it takes O(log n) steps.
The least common multiple, lcm, is the smallest number both divide. It comes straight from the gcd: lcm(a, b) = a / gcd(a, b) * b. Divide first, so the middle value stays small.
Modular arithmetic keeps big numbers small. When a problem says "return the answer modulo 10⁹ + 7", take % MOD after every addition and multiplication. Adding and multiplying work with remainders, so the final answer is the same.
To find primes up to n, the sieve of Eratosthenes crosses out the multiples of each prime, starting from its square. It takes O(n log log n). To test one number, check divisors only up to its square root.
02How to spot it
Reach for these tools when the problem:
- mentions divisors, multiples, "evenly divides", fractions to simplify, or things that repeat in cycles. That is gcd or lcm.
- asks for an answer "modulo 10⁹ + 7". Take the remainder as you go.
- asks about primes, or about factors of many numbers up to a limit. Use a sieve.
- has numbers too big to loop to, such as 10¹². You need a formula or an O(log n) method.
Also watch for sums with a closed form. The sum of 1 to n is n(n + 1) / 2. Checking that formula in your head is faster than a loop, and it avoids a time limit.
Sign in to read the rest of this lesson
The worked example, the interactive visualization, the code template and a short quiz that marks the lesson as done in your study plans.
Sign in to continue