Progress
🌍
Why does this topic matter?
Math is the hidden engine inside the most elegant algorithm solutions. Problems that look like they need O(N) brute-force often have O(log N) math-based shortcuts. Can you check if a number is prime in 17 steps instead of 1 million? Can you compute 21000 without overflow? Can you find GCD without a loop of a million iterations? The answer to all three is yes — and those answers appear directly in FAANG interviews at Google, Amazon, Microsoft, and Apple. You don't need a math degree. You need 6 patterns.

📖 Before We Start — The Big Picture

Mathematics gives algorithms their efficiency. Consider finding if a number N is prime. The naïve approach checks all divisors from 2 to N — that's O(N) steps. The mathematical observation that "factors come in pairs, and one is always ≤ √N" reduces it to O(√N). For N = 1,000,000 that's the difference between 1,000,000 checks and 1,000 checks.

Modular arithmetic is clock arithmetic — on a 12-hour clock, 11 + 3 = 2, not 14. This is how computers handle numbers larger than the maximum int value: instead of overflowing, we keep taking the remainder. The pattern "output mod 109+7" appears in almost every combinatorics or large-number problem on LeetCode.

🔗
How it connects: Lecture 6 (Bit Manipulation) introduced fast exponentiation using bit shifts — this lecture formalizes it as Binary Exponentiation. Lecture 8 (Arrays & Strings) frequently uses digit extraction (n % 10, n / 10) and mathematical observations to solve string/number problems efficiently.

🔢 Why Math Matters in FAANG Interviews

💡
You don't need a math degree. You need ~6 patterns:
Prime check · Sieve · GCD/LCM · Modular arithmetic · Fast exponentiation · Combinatorics

These appear at Google, Amazon, Apple, Microsoft — often as the key trick that turns O(n) into O(log n).
Pattern Example Problem Naive With Math
Prime check Is n prime? O(n) O(√n)
All primes up to N Count Primes (LC 204) O(n√n) O(n log log n)
GCD Largest common divisor O(min(a,b)) O(log min(a,b))
Modular power x^n mod m O(n) O(log n)
Combinations Count paths in grid Exponential O(n)

🔵 Prime Numbers

A number n is prime if it is > 1 and divisible only by 1 and itself. Every integer > 1 is either prime or a unique product of primes (Fundamental Theorem of Arithmetic).

Trial Division — O(√n)

🔑
Key Insight: If n has a factor > √n, it must also have one < √n (factors come in pairs). So only check divisors up to √n.
☕ Java · isPrime O(√n)
boolean isPrime(int n) {
    if (n < 2) return false;
    if (n == 2) return true;
    if (n % 2 == 0) return false;
    for (int i = 3; i * i <= n; i += 2)  // only odd divisors
        if (n % i == 0) return false;
    return true;
}
// isPrime(25): i=3(9≤25,25%3=1) i=5(25≤25,25%5=0) → false ✓ (25=5×5)
Time O(√n)
Space O(1)

Sieve of Eratosthenes — O(n log log n)

Find all primes up to N. Mark each prime's multiples as composite. Start marking at i² (smaller multiples already marked by earlier primes).

☕ Java · Sieve
boolean[] sieve(int n) {
    boolean[] comp = new boolean[n+1]; // false=prime
    comp[0] = comp[1] = true;
    for (int i = 2; (long)i*i <= n; i++)
        if (!comp[i])
            for (int j = i*i; j <= n; j += i) // start at i²
                comp[j] = true;
    return comp; // comp[i]=false → prime
}
Sieve(10): step by step Start: 2 3 4 5 6 7 8 9 10 i=2: mark 4,6,8,10 → left: 2 3 5 7 9 i=3: mark 9 → left: 2 3 5 7 i=4: 4×4=16 > 10, stop. Primes ≤10: 2, 3, 5, 7
Memory: Sieve uses O(n) space. For n=107 that's ~10MB. Use a segmented sieve for n > 108.

⚙ GCD & LCM — Euclidean Algorithm

📐
Core Formula: gcd(a, b) = gcd(b, a % b)   Base case: gcd(a, 0) = a
LCM: lcm(a, b) = (a / gcd(a,b)) * b  ← divide first to prevent overflow
☕ Java · GCD & LCM
int gcd(int a, int b) { return b == 0 ? a : gcd(b, a%b); }

int gcdIter(int a, int b) { // iterative (avoids stack overflow)
    while (b != 0) { int t = b; b = a%b; a = t; }
    return a;
}

long lcm(long a, long b) { return (a / gcd((int)a, (int)b)) * b; }

// gcd(48,18): →gcd(18,12) →gcd(12,6) →gcd(6,0) = 6 ✓
// lcm(4,6) = (4/2)*6 = 12 ✓
Time O(log min(a,b))
Space O(1)

🔄 Modular Arithmetic

When results exceed long range (e.g. 21000), use modular arithmetic. Most FAANG problems that say "output mod 109+7" require this.

📐
Rules (mod m):
(a+b) % m = ((a%m)+(b%m)) % m
(a×b) % m = ((a%m)×(b%m)) % m
(a−b) % m = ((a%m)−(b%m)+m) % m  ← +m prevents negatives!
Division: use modular inverse (Fermat's little theorem when m is prime)

Binary Exponentiation (Fast Power) — O(log n)

xn = (xn/2)2 if n is even  |  x × xn-1 if n is odd. This halves the exponent each step.

☕ Java · Binary Exponentiation
long fastPow(long base, long exp, long mod) {
    long result = 1;
    base %= mod;
    while (exp > 0) {
        if ((exp & 1) == 1) result = result * base % mod; // odd exp: accumulate
        base = base * base % mod;  // square the base
        exp >>= 1;                 // exp = exp/2
    }
    return result;
}
// fastPow(2,10,1000):
// exp=1010&sub2;: base=2,4,16,256
// Bits set at positions 1,3 → result = 4×256=1024 → 1024%1000=24 ✓
Time O(log n)
Space O(1)

🧮 Prime Factorization — O(√n)

☕ Java · Prime Factorization
Map<Integer,Integer> primeFactors(int n) {
    Map<Integer,Integer> f = new HashMap<>();
    for (int i = 2; (long)i*i <= n; i++)
        while (n % i == 0) { f.merge(i,1,Integer::sum); n /= i; }
    if (n > 1) f.put(n, 1);
    return f;
}
// 360 = 2³×3²×5 → {{2:3, 3:2, 5:1}}
// Divisor count = (3+1)(2+1)(1+1) = 24 divisors

🎲 Combinatorics — Counting Without Listing

📐
C(n,r) = n! / (r! × (n-r)!)   (n choose r)
Pascal's Rule: C(n,r) = C(n-1,r-1) + C(n-1,r)
Tip: C(n,r) = C(n,n-r)  ← always choose the smaller side to minimize computation
☕ Java · Pascal's Triangle
long[][] pascalTriangle(int n) {
    long[][] C = new long[n+1][n+1];
    for (int i = 0; i <= n; i++) {
        C[i][0] = 1;
        for (int j = 1; j <= i; j++)
            C[i][j] = C[i-1][j-1] + C[i-1][j]; // Pascal's Rule
    }
    return C;
}
// C[4][2] = C(4,2) = 6 ways to choose 2 from 4 ✓
Pascal's Triangle: Row 0: 1 Row 1: 1 1 Row 2: 1 2 1 Row 3: 1 3 3 1 Row 4: 1 4 6 4 1 ← C(4,2)=6 (paths in 4-step grid) Each number = sum of the two directly above (Pascal's Rule)

💪 In-Lecture Practice Problems

Work through in order. Click a card to expand. Try solving before revealing the solution.

Problem 01 · Sieve
Count Primes
Easy Google Amazon Sieve
Problem 02 · GCD Pattern
GCD of Array
Easy Amazon GCD
Problem 03 · Fast Power
Pow(x, n)
Medium Google Facebook Binary Exp
Problem 04 · Digit Math
Happy Number
Easy Amazon Microsoft Cycle Detection
Problem 05 · Combinatorics
Unique Paths
Medium Google Amazon Apple Math / DP
Problem 06 · Pascal's Triangle
Pascal's Triangle Row (O(n) space)
Easy Apple Microsoft Combinatorics
Problem 07 · Base Conversion
Excel Sheet Column Title
Easy Microsoft Amazon Math / Encoding
Problem 08 · Prime Factorization
Ugly Number II — Smallest with only 2, 3, 5 as factors
Medium Google Amazon Three Pointers

📝 Assignment

📋
Lecture 7 Assignment — 30 Problems
Primes, modular arithmetic, GCD patterns, combinatorics, number theory tricks. Complete before starting Lecture 8.
📄 Open Assignment →

✅ Lecture Completion Checklist

Don't proceed to Lecture 8 until all are checked.

I can check if n is prime in O(√n) without notes
I can implement the Sieve of Eratosthenes from memory and explain why inner loop starts at i²
I can implement gcd(a,b) recursively and iteratively and derive lcm from it
I know all 4 modular arithmetic rules — especially (a-b)%m needs +m to prevent negatives
I can implement fastPow(base, exp, mod) using binary exponentiation from memory
I understand Pascal's Rule C(n,r)=C(n-1,r-1)+C(n-1,r) and can build the triangle in O(n²)
I solved Count Primes (LC 204) with Sieve — not brute force
I solved Unique Paths (LC 62) using C(m+n-2, m-1) math — not only DP
I can state: isPrime O(√n), Sieve O(n log log n), GCD O(log n), fastPow O(log n)
I completed at least 12 problems from the Assignment
🚀
You're ready for Lecture 8: Arrays & Strings!
Phase 2 begins — The most common interview category (40%+ of FAANG questions).
← Topic 6: Bit ManipulationTopic 8: Arrays & Strings →