Logic, Concepts, and Deep Understanding
Number theory is the branch of mathematics that studies the properties and relationships of integers. In programming interviews, it helps us solve problems involving:
Number theory appears in:
A prime number is a natural number greater than 1 that has exactly two factors: 1 and itself.
To check if n is prime, test if any number from 2 to n-1 divides n.
If n has a factor greater than โn, it must also have a factor less than โn!
Consider n = a ร b where a โค b
โ49 = 7, so we only check divisors up to 7
Result: 49 is not prime (49 = 7 ร 7)
Instead of checking each number individually, eliminate all composite numbers systematically.
GCD (Greatest Common Divisor): Largest number that divides both a and b
LCM (Least Common Multiple): Smallest number that both a and b divide
GCD(a, b) = GCD(b, a mod b)
If d divides both a and b, then:
This means any common divisor of (a,b) is also a common divisor of (b, a mod b)
Verification: 48 = 6ร8, 18 = 6ร3, so GCD is indeed 6!
Working with remainders instead of actual numbers. It's like clock arithmetic!
Computing a^b mod m directly can overflow for large numbers!
Calculate 2^1000 mod 1000000007
Key insight: a^b = (a^(b/2))^2 when b is even
Verification: 3^10 = 59049, 59049 mod 7 = 4 โ
ฯ(n) = count of integers from 1 to n that are coprime to n (GCD = 1)
For a prime p: ฯ(p) = p - 1 (all numbers except multiples of p)
12 = 2ยฒ ร 3, so prime factors are 2 and 3
Verification: Numbers coprime to 12: {1, 5, 7, 11} โ Count = 4 โ
Divisors of n are all positive integers that divide n evenly.
Divisors come in pairs! If d divides n, then n/d also divides n.
โ36 = 6, so check 1, 2, 3, 4, 5, 6
Result: {1, 2, 3, 4, 6, 9, 12, 18, 36}
A perfect number equals the sum of its proper divisors (excluding itself).
Problem Type | Key Concept | Example Problems |
---|---|---|
Prime Checking | Optimized โn algorithm | Count Primes, Prime Factorization |
Bulk Prime Finding | Sieve of Eratosthenes | Find all primes in range |
Common Factors | Euclidean Algorithm | Simplify fractions, array GCD |
Large Exponents | Fast modular exponentiation | Power calculations, RSA crypto |
Counting Problems | Euler's totient function | Coprime counting, cyclic groups |