Skip to main content
✦ Reference Hub

Math for DSA ∑

You don't need to be a mathematician — but knowing these formulas and properties cold saves you critical minutes in an interview. Every topic here appears repeatedly in LeetCode medium/hard problems.

1. Number Theory Fundamentals

ConceptDefinition / FormulaKey Fact
Divisibilitya | b means b = a × k for some integer ka | b and a | c → a | (b + c)
PrimeDivisible only by 1 and itselfCheck up to √n only — O(√n) primality test
CompositeHas a factor ≤ √nEvery composite n has a prime factor ≤ √n
GCDLargest number dividing both a and bgcd(a, b) = gcd(b, a % b) — Euclidean algorithm
LCMSmallest multiple of both a and blcm(a,b) = a × b / gcd(a,b). Divide first!
Coprimegcd(a, b) = 1Consecutive integers are always coprime
Prime factorizationEvery integer = product of primesUnique (Fundamental Theorem of Arithmetic)
Number of divisorsIf n = p1^a1 × p2^a2 × ..., count = (a1+1)(a2+1)...Highly composite numbers have many divisors
C++
// O(sqrt(n)) primality test
bool isPrime(long long n) {
    if (n < 2) return false;
    if (n == 2 || n == 3) return true;
    if (n % 2 == 0 || n % 3 == 0) return false;
    for (long long i = 5; i * i <= n; i += 6)
        if (n % i == 0 || n % (i + 2) == 0) return false;
    return true;
}

// Prime factorization
map<int,int> factorize(int n) {
    map<int,int> factors;
    for (int i = 2; i * i <= n; i++)
        while (n % i == 0) { factors[i]++; n /= i; }
    if (n > 1) factors[n]++;
    return factors;
}
Java
boolean isPrime(long n) {
    if (n < 2) return false;
    if (n == 2 || n == 3) return true;
    if (n % 2 == 0 || n % 3 == 0) return false;
    for (long i = 5; i * i <= n; i += 6)
        if (n % i == 0 || n % (i + 2) == 0) return false;
    return true;
}
Python
def is_prime(n):
    if n < 2: return False
    if n < 4: return True
    if n % 2 == 0 or n % 3 == 0: return False
    i = 5
    while i * i <= n:
        if n % i == 0 or n % (i + 2) == 0: return False
        i += 6
    return True

2. Modular Arithmetic — The Complete Rules

Why MOD = 10⁹ + 7?

It's the largest prime that fits in a 32-bit integer with room to multiply two values without overflowing a 64-bit integer (since (10⁹+6)² < 2⁶³). It's prime, enabling modular inverse via Fermat's little theorem.

PropertyFormulaWatch out for
Addition(a + b) % m = ((a % m) + (b % m)) % mAlways safe
Subtraction(a - b) % m = ((a % m) - (b % m) + m) % mAdd m before modding — result can be negative
Multiplication(a × b) % m = ((a % m) × (b % m)) % mCast to long/int64 before multiplying
Division(a / b) % m = (a × b⁻¹) % mOnly valid when m is prime and gcd(b, m) = 1
Modular inverseb⁻¹ = b^(m-2) mod mFermat's little theorem — requires m prime
Power(a^n) % m = ((a % m)^n) % mUse fast exponentiation
⚠ Most Common Modular Arithmetic Mistakes
  • Forgetting to cast to long in C++/Java: int a = 1e9; a * a overflows. Use (long long)a * a % MOD.
  • Dividing directly: (a / b) % MOD ≠ a % MOD / b % MOD. Use modular inverse instead.
  • Negative results: In C++, -1 % 7 is -1, not 6. Always add MOD after subtraction.
  • Python is safe: Python's % always returns non-negative for positive modulus. C++/Java do not.

3. Powers of 2 — Memorize These

These appear constantly in binary search, DP, bitmask problems, and memory calculations.

PowerValueApproxWhere it appears
2¹⁰1,024~10³1 KB
2¹⁶65,536~6.5×10⁴Max unsigned short
2²⁰1,048,576~10⁶1 MB (in bytes)
2²³8,388,608~8×10⁶Float mantissa bits
2³⁰1,073,741,824~10⁹Close to INT_MAX / 2
2³¹ − 12,147,483,647~2.1×10⁹INT_MAX in 32-bit signed
2³²4,294,967,296~4.3×10⁹Max unsigned int
2⁶³ − 19,223,372,036,854,775,807~9.2×10¹⁸LONG_MAX in 64-bit signed

4. Combinatorics

FormulaWhat it countsExample
n!Permutations of n distinct items3! = 6 orderings of {A,B,C}
P(n,r) = n!/(n-r)!Ordered selections of r from nP(5,2) = 20 ordered pairs
C(n,r) = n! / (r!(n-r)!)Unordered selections of r from nC(5,2) = 10 pairs
2ⁿAll subsets of n items2³ = 8 subsets of {A,B,C}
C(n+r-1, r)Combinations with repetitionDistribute n identical items in r bins
n! / (n1! × n2! × ...)Permutations with duplicatesMISSISSIPPI: 11!/(4!×4!×2!)
Catalan(n) = C(2n,n)/(n+1)BST shapes, valid parens, triangulationsC(0..7) = 1,1,2,5,14,42,132,429

Pascal's Triangle (nCr mod p)

C++
// Precompute C(n, r) mod p for all n, r <= MAXN
const int MAXN = 1001, MOD = 1e9 + 7;
long long C[MAXN][MAXN];

void precompute() {
    for (int i = 0; i < MAXN; i++) {
        C[i][0] = 1;
        for (int j = 1; j <= i; j++)
            C[i][j] = (C[i-1][j-1] + C[i-1][j]) % MOD;
    }
}
Java
static final int MOD = 1_000_000_007;
long[][] C = new long[1001][1001];

void precompute() {
    for (int i = 0; i < 1001; i++) {
        C[i][0] = 1;
        for (int j = 1; j <= i; j++)
            C[i][j] = (C[i-1][j-1] + C[i-1][j]) % MOD;
    }
}
Python
from math import comb  # Python 3.8+
comb(10, 3)  # 120

# Manual Pascal's triangle
MOD = 10**9 + 7
MAXN = 1001
C = [[0] * MAXN for _ in range(MAXN)]
for i in range(MAXN):
    C[i][0] = 1
    for j in range(1, i + 1):
        C[i][j] = (C[i-1][j-1] + C[i-1][j]) % MOD

5. Series & Sequences — Closed Forms

These let you replace O(N) loops with O(1) formulas. Know them cold.

SeriesFormulaExample
Sum 1 to NN(N+1)/21+2+...+100 = 5050
Sum of squaresN(N+1)(2N+1)/61²+2²+...+N²
Sum of cubes[N(N+1)/2]²1³+2³+...+N³ = (N(N+1)/2)²
Geometric seriesa(rⁿ - 1)/(r - 1)1+2+4+...+2ⁿ⁻¹ = 2ⁿ - 1
Harmonic series1 + 1/2 + 1/3 + ... + 1/N ≈ ln(N)Appears in Sieve analysis
Sum of first N odds1+3+5+...+(2N-1) = N²
Fibonacci (closed form)F(n) = (φⁿ - ψⁿ)/√5φ = (1+√5)/2 ≈ 1.618 (golden ratio)

6. Logarithm Properties

PropertyFormulaUse in DSA
Product rulelog(a × b) = log(a) + log(b)Converting multiplication to addition
Quotient rulelog(a / b) = log(a) - log(b)
Power rulelog(aⁿ) = n × log(a)Height of balanced tree with n nodes = log₂(n)
Change of baselog_b(a) = log(a) / log(b)Convert between log₂ and log₁₀
Binary search steps⌊log₂(N)⌋ + 1Max iterations to find in sorted array of size N
Tree height⌊log₂(N)⌋Height of complete binary tree with N nodes
Useful identitylog₂(N) ≈ log(N) / 0.301Convert natural log to log base 2

7. Important Constants & Limits

ConstantValueC++JavaPython
INT_MAX2,147,483,647INT_MAXInteger.MAX_VALUEfloat('inf')
INT_MIN-2,147,483,648INT_MINInteger.MIN_VALUEfloat('-inf')
LONG_MAX9.2 × 10¹⁸LLONG_MAXLong.MAX_VALUEN/A (arbitrary precision)
MOD (common)1,000,000,0071e9 + 71_000_000_00710**9 + 7
MOD (alt)998,244,353998244353998244353998244353
√2≈ 1.41421356sqrt(2)Math.sqrt(2)2**0.5
π≈ 3.14159265M_PIMath.PImath.pi

8. Overflow Prevention

⚠ Overflow is silent and deadly

Overflow in C++/Java doesn't throw an error — it wraps around silently and produces wrong answers that pass some test cases. Python has arbitrary precision integers so overflow is never an issue.

SituationDangerFix
a * b where a,b ~ 10⁹int overflow (max ~2.1×10⁹)Cast: (long long)a * b
lo + hi in binary searchint overflow when lo + hi > INT_MAXUse lo + (hi - lo) / 2
n * (n-1) for n ~ 10⁵int overflow at n ≥ ~46,341Use (long long)n * (n-1)
LCM of large numbersa * b overflows before dividing by gcdUse a / gcd(a,b) * b (divide first)
DP accumulation over 10⁵ stepsint overflows if each step adds ~10⁴Use long/int64
Factorial n! for n > 12int overflow; n=13 → 6.2×10⁹Use long (safe to n=20); beyond → BigInteger/Python

9. Integer Division, Floor & Ceil

OperationC++JavaPythonGotcha
Floor divisiona / b (truncates toward 0)a / b (truncates toward 0)a // b (floors toward -∞)C++/Java: -7/2 = -3, Python: -7//2 = -4
Ceiling division(a + b - 1) / b(a + b - 1) / b-(-a // b) or math.ceil(a/b)Classic trick: ceil(a/b) = (a+b-1)/b for positive
Modulo negative-7 % 3 = -1-7 % 3 = -1-7 % 3 = 2Python always non-negative for positive divisor
Round half up(a + b/2) / b(a + b/2) / bround(a/b) (banker's rounding!)Python round() uses banker's rounding (round half to even)
⚠ Points to Remember
  • In Python, -7 // 2 = -4 (floors toward negative infinity). In C++/Java, -7 / 2 = -3 (truncates toward zero). This difference causes subtle bugs in modular arithmetic.
  • Always use integer types for bit operations. Floating-point bit manipulation is undefined behavior in C++.
  • For combinatorics with large n, precompute factorials and inverse factorials mod p, then compute nCr = fact[n] * inv_fact[r] * inv_fact[n-r] % p.
  • The Pigeonhole Principle: if N+1 items fit in N buckets, at least one bucket has 2 items. Useful for proving existence of duplicates.
Buy me a coffee