DK-002 — Math Every Programmer Should Know


🎯 Why This Note Exists

Programming is the art of turning ideas into systems. Mathematics is the art of thinking clearly about those systems.

You don’t need advanced math. But if you are a programmer, there are equations you must recognize instinctively.

This note presents 87 essential math equations, each with:

  • Plain explanation
  • Concrete input → output examples (like test cases)
  • Pure Python code only (no libraries, no shortcuts)

If math feels friendly, coding becomes powerful and fun.


🔢 GCD & LCM — The Backbone of Discrete Math for Programmers


🔹 Greatest Common Divisor (GCD)

Definition

The Greatest Common Divisor (GCD) of two integers a and b is the largest integer that divides both without remainder.


📐 GCD — Euclidean Algorithm

$$ \gcd(a, b) = \gcd(b, a \bmod b) $$

This works because:

Dividing by the remainder preserves common divisors.


✅ Input → Output (Test Cases)

a b gcd(a,b)
12 18 6
20 8 4
17 5 1
100 25 25

🧑‍💻 Pure Python Code (No Library)

def gcd(a, b):
    while b != 0:
        a, b = b, a % b
    return a

print(gcd(12, 18))   # 6
print(gcd(20, 8))    # 4
print(gcd(17, 5))    # 1
print(gcd(100, 25))  # 25

🧠 Helps Solve

  • Fraction simplification
  • Ratio normalization
  • Periodic cycles
  • Cryptography (RSA basics)
  • Grid / tiling problems

🧩 Typical Questions

  • “Simplify this fraction”
  • “Do these two cycles ever align?”
  • “What is the repeating interval?”

🧠 Builds Intuition

Repeated subtraction is slow. Remainders reveal structure faster.


🔹 Least Common Multiple (LCM)

Definition

The Least Common Multiple (LCM) of two integers is the smallest positive number divisible by both.


📐 Relationship Between GCD and LCM

$$ \text{lcm}(a, b) = \frac{a \times b}{\gcd(a, b)} $$

This identity is critical and used everywhere.


✅ Input → Output (Test Cases)

a b lcm(a,b)
4 6 12
5 7 35
8 12 24
6 15 30

🧑‍💻 Pure Python Code

def gcd(a, b):
    while b != 0:
        a, b = b, a % b
    return a

def lcm(a, b):
    return a * b // gcd(a, b)

print(lcm(4, 6))    # 12
print(lcm(5, 7))    # 35
print(lcm(8, 12))   # 24
print(lcm(6, 15))   # 30

🧠 Helps Solve

  • Synchronization problems
  • Scheduling systems
  • Clock / cycle alignment
  • Repeating events

🧩 Typical Questions

  • “When will these two jobs run together again?”
  • “What is the smallest shared interval?”

🧠 Builds Intuition

GCD removes overlap. LCM rebuilds alignment.


🔁 GCD & LCM Together — Real Insight

📐 Identity to Remember Forever

$$ \gcd(a,b) \times \text{lcm}(a,b) = a \times b $$


✅ Quick Verification (Test)

a, b = 12, 18
print(gcd(a, b) * lcm(a, b) == a * b)

Output

True

🧠 Why This Matters for Programmers

  • Prevents overflow logic errors
  • Enables optimal loop bounds
  • Unlocks number theory problems
  • Appears in interviews constantly

🎯 Mental Model (Very Important)

GCD answers: “What do these numbers share?”

LCM answers: “When do they meet again?”

If a problem mentions:

  • sharing → think GCD
  • alignment / repetition → think LCM

5️⃣ Prime Numbers

📘 What Is a Prime Number?

A prime number is a number that:

Has exactly two divisors: 1 and itself

Examples:

  • Prime: 2, 3, 5, 7, 11
  • Not prime: 1, 4, 6, 8, 9

🧠 Mathematical Definition

For a number n:

$$ n > 1 \quad \text{and} \quad n \bmod k \neq 0 ;; \forall k \in [2, \sqrt{n}] $$


✅ Input → Output (Test Cases)

n Is Prime
2 True
3 True
4 False
9 False
13 True

🐍 Pure Python Code

def is_prime(n):
    if n <= 1:
        return False

    i = 2
    while i * i <= n:
        if n % i == 0:
            return False
        i += 1

    return True

# Tests
print(is_prime(2))   # True
print(is_prime(9))   # False
print(is_prime(13))  # True

💡 Why Programmers Care

Used in:

  • Security & cryptography
  • Hashing
  • Random number systems

Mental model:

Primes are the atoms of numbers.


6️⃣ Modular Arithmetic (%)

📘 What Is Modulo?

Modulo gives the remainder after division.

$$ a \bmod b $$

Example:

  • 17 % 5 = 2

🧠 Everyday Intuition

Clock arithmetic:

  • (9 + 5) % 12 = 2
  • Time wraps around

✅ Input → Output (Test Cases)

Expression Result
10 % 3 1
14 % 7 0
23 % 4 3

🐍 Pure Python Code

print(10 % 3)   # 1
print(14 % 7)   # 0
print(23 % 4)   # 3

💡 Why Modulo Is Everywhere

Used in:

  • Index wrapping
  • Cyclic buffers
  • Hash tables
  • Cryptography

Mental model:

Modulo keeps numbers bounded.


7️⃣ Fractions & Simplification

📘 What Is a Fraction?

A fraction represents a ratio:

$$ \frac{a}{b} $$

Example:

  • 8 / 12 = 2 / 3

🧠 Simplification Rule

Divide numerator and denominator by their GCD:

$$ \frac{a}{b} = \frac{a \div \gcd(a, b)}{b \div \gcd(a, b)} $$


✅ Input → Output (Test Cases)

Fraction Simplified
8/12 2/3
10/20 1/2
7/9 7/9

🐍 Pure Python Code

def gcd(a, b):
    while b != 0:
        a, b = b, a % b
    return a

def simplify_fraction(a, b):
    g = gcd(a, b)
    return a // g, b // g

# Tests
print(simplify_fraction(8, 12))   # (2, 3)
print(simplify_fraction(10, 20))  # (1, 2)
print(simplify_fraction(7, 9))    # (7, 9)

💡 Why This Matters

Used in:

  • Percentages
  • Financial calculations
  • Scaling systems

Mental model:

Reduce before you reason.


8️⃣ Powers & Logarithms

📘 Powers (Exponents)

$$ a^n = a \times a \times \dots \times a $$

Example:

  • 2^5 = 32

🧠 Logarithms (Opposite of Power)

$$ \log_b(x) = n \quad \text{means} \quad b^n = x $$

Example:

  • log₂(8) = 3

✅ Input → Output (Test Cases)

Expression Result
2^4 16
3^3 27
log₂(8) 3

🐍 Pure Python Code (No Libraries)

def power(a, n):
    result = 1
    for _ in range(n):
        result *= a
    return result

def log_base(b, x):
    count = 0
    while x > 1:
        x //= b
        count += 1
    return count

# Tests
print(power(2, 4))      # 16
print(power(3, 3))      # 27
print(log_base(2, 8))   # 3

💡 Programmer Insight

  • Powers grow fast
  • Logs grow slow

Mental model:

Logs explain why algorithms scale.


9️⃣ Fibonacci Sequence

📘 What Is Fibonacci?

A sequence where:

$$ F(n) = F(n-1) + F(n-2) $$

Starting values:

  • F(0) = 0
  • F(1) = 1

Sequence:

0, 1, 1, 2, 3, 5, 8, 13, ...

✅ Input → Output (Test Cases)

n F(n)
0 0
1 1
5 5
8 21

🐍 Pure Python Code (Iterative)

def fibonacci(n):
    if n == 0:
        return 0
    if n == 1:
        return 1

    a, b = 0, 1
    for _ in range(2, n + 1):
        a, b = b, a + b
    return b

# Tests
print(fibonacci(0))  # 0
print(fibonacci(1))  # 1
print(fibonacci(5))  # 5
print(fibonacci(8))  # 21

💡 Why Fibonacci Is Taught

Used to teach:

  • Recursion vs iteration
  • Dynamic programming
  • Growth patterns

Mental model:

The present depends on the past.


🏁 Final Thought for Students

Math is not about numbers. It’s about patterns.

Once you see patterns, code becomes a language for expressing them.


🔟 Big-O Intuition (Algorithm Growth)

📘 What Is Big-O?

Big-O describes how fast an algorithm grows as input size n increases.

It ignores:

  • Constants
  • Hardware
  • Language

It focuses on:

Growth trend


🧠 Common Big-O Forms

Big-O Meaning Example
O(1) Constant Access array
O(n) Linear Loop
O(n²) Quadratic Nested loops
O(log n) Logarithmic Binary search

🧪 Example: Linear vs Quadratic

def linear(n):
    count = 0
    for _ in range(n):
        count += 1
    return count

def quadratic(n):
    count = 0
    for _ in range(n):
        for _ in range(n):
            count += 1
    return count

print(linear(5))     # 5
print(quadratic(5))  # 25

💡 Mental Model

  • Loops → add n
  • Nested loops → multiply n
  • Halving each step → log n

Big-O is about how pain grows.


1️⃣1️⃣ Probability Basics

📘 What Is Probability?

Probability measures how likely an event is.

$$ P(event) = \frac{\text{favorable outcomes}}{\text{total outcomes}} $$


🧠 Examples

  • Coin flip:

    • Heads = 1 / 2
  • Dice roll:

    • Rolling a 6 = 1 / 6

✅ Input → Output (Test Cases)

Scenario Probability
Coin heads 0.5
Dice 6 ~0.1667

🐍 Pure Python Code

def probability(favorable, total):
    return favorable / total

# Tests
print(probability(1, 2))   # 0.5
print(probability(1, 6))   # 0.1666...

💡 Programmer Insight

Used in:

  • Randomized algorithms
  • Simulations
  • AI & ML
  • Risk systems

Mental model:

Probability quantifies uncertainty.


1️⃣2️⃣ Bitwise Math

📘 What Are Bits?

Computers think in binary:

0 or 1

Bitwise operations work at this level.


🧠 Common Bitwise Operators

Operator Meaning
& AND
OR OR
^ XOR
<< Left shift
>> Right shift

🧪 Examples

print(5 & 3)   # 1   (101 & 011)
print(5 | 3)   # 7   (101 | 011)
print(5 ^ 3)   # 6   (101 ^ 011)
print(1 << 3)  # 8
print(8 >> 2)  # 2

💡 Why Bitwise Matters

Used in:

  • Performance optimization
  • Flags & permissions
  • Cryptography
  • Low-level systems

Mental model:

Bits are switches.


1️⃣3️⃣ Matrix Basics

📘 What Is a Matrix?

A matrix is a 2D grid of numbers.

Example:

$$ \begin{bmatrix} 1 & 2
3 & 4 \end{bmatrix} $$


🧠 Matrix Addition Rule

Same size matrices:

$$ C[i][j] = A[i][j] + B[i][j] $$


🐍 Pure Python Code

def add_matrices(A, B):
    result = []
    for i in range(len(A)):
        row = []
        for j in range(len(A[0])):
            row.append(A[i][j] + B[i][j])
        result.append(row)
    return result

# Tests
A = [[1, 2], [3, 4]]
B = [[5, 6], [7, 8]]

print(add_matrices(A, B))
# [[6, 8], [10, 12]]

💡 Programmer Insight

Used in:

  • Graphics
  • Machine learning
  • Games
  • Transformations

Mental model:

Matrices transform space.


1️⃣4️⃣ Math Behind Hashing

📘 What Is Hashing?

Hashing maps data of any size to a fixed-size number.

Example:

"cat" → 312
"dog" → 417

🧠 Core Properties

A good hash:

  • Is fast
  • Distributes evenly
  • Is deterministic

🧪 Simple Hash Formula

$$ hash = (hash \times base + value) \bmod size $$


🐍 Pure Python Hash Example

def simple_hash(s, size=100):
    h = 0
    for ch in s:
        h = (h * 31 + ord(ch)) % size
    return h

# Tests
print(simple_hash("cat"))
print(simple_hash("dog"))
print(simple_hash("cat"))  # same every time

💡 Why Hashing Matters

Used in:

  • Dictionaries
  • Sets
  • Databases
  • Password storage

Mental model:

Hashing turns structure into position.


🧠 Final Wisdom for Programmers

Math is not school math. It’s thinking math.

When you understand:

  • Growth (Big-O)
  • Uncertainty (Probability)
  • Structure (Bits & Matrices)
  • Mapping (Hashing)

You stop guessing and start designing.


1️⃣5️⃣ Differentiation (Derivative)

📘 What is Differentiation?

Differentiation measures how a function changes as its input changes. In simple terms:

The derivative tells us the slope of a function at any point.


🧠 Mathematical Definition

For a function (f(x)):

$$ f’(x) = \lim_{h \to 0} \frac{f(x+h) - f(x)}{h} $$

Intuition:

  • How steep is the curve at point x?
  • Rate of change.

✅ Input → Output (Examples)

Function x f’(x)
f(x) = x² 3 6
f(x) = 3x³ 2 36
f(x) = 5x 4 5
f(x) = 7 10 0

🐍 Pure Python Code (Numerical Derivative)

def derivative(f, x, h=1e-5):
    return (f(x + h) - f(x)) / h

# Test functions
def f1(x): return x**2
def f2(x): return 3*x**3
def f3(x): return 5*x
def f4(x): return 7

# Tests
print(derivative(f1, 3))  # ~6
print(derivative(f2, 2))  # ~36
print(derivative(f3, 4))  # ~5
print(derivative(f4, 10)) # ~0

💡 Programmer Insight

  • Used in physics simulations: velocity = derivative of position
  • Optimization: slope = gradient
  • Machine learning: gradient descent

Mental model:

Derivative = “how fast things change”.


1️⃣6️⃣ Integration (Integral)

📘 What is Integration?

Integration measures the area under a curve. In simple terms:

Integration tells us the total accumulated quantity.


🧠 Mathematical Definition

For a function (f(x)):

$$ \int_a^b f(x) dx \approx \text{area under } f(x) \text{ from } x=a \text{ to } x=b $$


✅ Input → Output (Examples)

Function Interval Integral (Approx)
f(x) = x 0→3 4.5
f(x) = x² 0→2 8/3 ≈ 2.6667
f(x) = 3x³ 1→2 15

🐍 Pure Python Code (Numerical Integration via Rectangle Method)

def integrate(f, a, b, n=1000):
    dx = (b - a) / n
    total = 0
    for i in range(n):
        total += f(a + i*dx) * dx
    return total

# Test functions
def f1(x): return x
def f2(x): return x**2
def f3(x): return 3*x**3

# Tests
print(integrate(f1, 0, 3))     # ~4.5
print(integrate(f2, 0, 2))     # ~2.6667
print(integrate(f3, 1, 2))     # ~15

🧪 Step-by-Step Example

Integral of f(x) = x from 0 to 3:

Divide interval [0,3] into 1000 rectangles
Each width dx = 0.003
Sum: dx * (f(0) + f(0.003) + ... + f(2.997)) ≈ 4.5

💡 Programmer Insight

  • Used in physics: distance = ∫ velocity dt
  • Probability: area under PDF
  • Graphics: total light, area, volume

Mental model:

Integral = “sum of infinitely many tiny pieces”.


1️⃣7️⃣ Linking Derivative & Integral

  • Derivative → rate of change
  • Integral → accumulated change

They are inverse operations:

$$ \frac{d}{dx} \int f(x) dx = f(x) $$

$$ \int \frac{d}{dx} f(x) dx = f(x) + C $$


🐍 Demonstration (Check Inverse)

def f(x): return x**2

# Derivative at x
x = 3
print(derivative(f, x))  # ~6

# Integral from 0 to x
print(integrate(lambda t: 2*t, 0, x))  # ~9, matches f(3)-f(0)

💡 Final Insight

  • Derivatives help you understand local behavior
  • Integrals help you accumulate global behavior
  • Together, they form the calculus toolbox for programming and simulation

Mental model:

Derivative = speed, Integral = distance traveled


1️⃣8️⃣ Partial Derivatives & Chain Rule

📘 What is a Partial Derivative?

A partial derivative measures how a multivariable function changes with respect to one variable, keeping the others constant.

Example: (f(x, y) = x^2y + 3y)

  • Partial derivative wrt (x):

$$ \frac{\partial f}{\partial x} = 2xy $$

  • Partial derivative wrt (y):

$$ \frac{\partial f}{\partial y} = x^2 + 3 $$


✅ Input → Output (Examples)

f(x, y) ∂f/∂x ∂f/∂y
x²y + 3y 2xy x² + 3
x*y + y² y x + 2y

🐍 Pure Python Code (Numerical Partial Derivative)

def partial_derivative(f, x, y, var='x', h=1e-5):
    if var == 'x':
        return (f(x+h, y) - f(x, y)) / h
    elif var == 'y':
        return (f(x, y+h) - f(x, y)) / h
    else:
        raise ValueError("var must be 'x' or 'y'")

# Test function
def f(x, y): return x**2 * y + 3*y

print(partial_derivative(f, 2, 3, 'x'))  # ~12
print(partial_derivative(f, 2, 3, 'y'))  # ~7

📘 What is the Chain Rule?

The chain rule lets you compute derivatives of nested functions:

If (z = f(g(x))):

$$ \frac{dz}{dx} = \frac{dz}{dg} \cdot \frac{dg}{dx} $$

Example: (z = (3x + 2)^2)

  • g(x) = 3x + 2
  • f(g) = g²
  • dz/dx = f’(g) * g’(x) = 2g * 3 = 6*(3x + 2)

🐍 Pure Python Code (Numerical Chain Rule)

def chain_rule(f, g, x, h=1e-5):
    g_x = g(x)
    df_dg = (f(g_x + h) - f(g_x)) / h
    dg_dx = (g(x + h) - g_x) / h
    return df_dg * dg_dx

# Example: z = (3x + 2)^2
def f(g): return g**2
def g(x): return 3*x + 2

print(chain_rule(f, g, 1))  # ~30, same as 6*(3*1+2)

1️⃣9️⃣ Backpropagation in Neural Networks

📘 What is Backpropagation?

Backpropagation uses chain rule + partial derivatives to compute gradients of loss wrt each weight.

  • Goal: Update weights to minimize loss
  • Uses derivative of loss wrt weights

🧠 Intuition with a Tiny Neural Network

x → [w1] → h = w1*x → [w2] → y_hat = w2*h
Loss L = (y_hat - y_true)^2
  • Step 1: Compute forward: h, y_hat
  • Step 2: Compute ∂L/∂w2 = ∂L/∂y_hat * ∂y_hat/∂w2
  • Step 3: Compute ∂L/∂w1 = ∂L/∂y_hat * ∂y_hat/∂h * ∂h/∂w1

This is just chain rule in action.


🐍 Pure Python Example (Single Neuron)

# Inputs
x = 2.0
y_true = 10.0
w1 = 0.5
w2 = 1.0
lr = 0.1  # learning rate

# Forward pass
h = w1 * x
y_hat = w2 * h
loss = (y_hat - y_true)**2
print("Initial loss:", loss)

# Backward pass (manual derivatives)
dL_dyhat = 2 * (y_hat - y_true)
dL_dw2 = dL_dyhat * h
dL_dw1 = dL_dyhat * w2 * x

# Update weights
w1 -= lr * dL_dw1
w2 -= lr * dL_dw2

print("Updated w1, w2:", w1, w2)

✅ Step-by-Step Example

  • Forward: h = 0.5 * 2 = 1, y_hat = 1 * 1 = 1

  • Loss: (1 - 10)² = 81

  • Derivative: ∂L/∂w2 = 2*(1-10)*1 = -18

  • Update: w2_new = 1 - 0.1*(-18) = 2.8

  • Derivative: ∂L/∂w1 = 2*(1-10)12 = -36

  • Update: w1_new = 0.5 - 0.1*(-36) = 4.1

Chain rule applied automatically through the chain of computations.


💡 Programmer Insight

  • Backprop = chain rule over networks
  • Allows neural networks to learn efficiently
  • Generalizes to any depth (deep learning)

Mental model:

Forward = compute output, Backward = compute “how each weight affects loss”


2️⃣0️⃣ Logarithms (Detailed Recap)

📘 What is a Logarithm?

A logarithm answers the question:

“To what power must I raise a base to get a number?”

Mathematically:

$$ \log_b(x) = y \quad \text{means} \quad b^y = x $$

  • b = base (must be >0, ≠1)
  • x = number (must be >0)
  • y = logarithm value

🧠 Examples

Expression Meaning Result
log₂(8) 2^? = 8 3
log₁₀(1000) 10^? = 1000 3
ln(e^2) e^? = e² 2

ln(x) = natural log = log base e (~2.718)


✅ Basic Properties of Logarithms

  1. Log of 1:

$$ \log_b(1) = 0 \quad \text{because } b^0 = 1 $$

  1. Log of the base:

$$ \log_b(b) = 1 \quad \text{because } b^1 = b $$

  1. Product Rule:

$$ \log_b(xy) = \log_b(x) + \log_b(y) $$

  1. Quotient Rule:

$$ \log_b(x/y) = \log_b(x) - \log_b(y) $$

  1. Power Rule:

$$ \log_b(x^k) = k \cdot \log_b(x) $$

  1. Change of Base Formula:

$$ \log_b(x) = \frac{\log_k(x)}{\log_k(b)} $$


🧪 Step-by-Step Example

Compute log₂(32):

2^? = 32
2^5 = 32
→ log₂(32) = 5

Check using product rule:

log₂(32) = log₂(2*16) = log₂(2) + log₂(16) = 1 + 4 = 5

🐍 Pure Python Code (Numerical Logarithms)

import math

# Basic logs
print(math.log2(8))     # 3
print(math.log10(1000)) # 3
print(math.log(math.e)) # 1 (natural log base e)

# Natural log
print(math.log(math.e**2))  # 2

# Change of base
def log_base(x, b):
    return math.log(x) / math.log(b)

print(log_base(32, 2))  # 5

🧠 Visual Intuition

  • Logarithms grow slowly compared to linear or exponential functions.
  • They “compress” large numbers into smaller scales.
x log₂(x)
1 0
2 1
4 2
8 3
16 4
32 5

Log is the inverse of exponentiation.


💡 Applications in Programming

  1. Algorithm analysis: Binary search → O(log n)
  2. Data compression & scaling: e.g., decibels, log scales
  3. Probability / Information theory: Entropy uses log
  4. Machine learning: Log loss, softmax, log probabilities

🧪 Quick Exercises

Compute:

  1. log₂(64) → 2^? = 64 → 6 ✅
  2. log₁₀(100) → 10^? = 100 → 2 ✅
  3. ln(e^5) → e^? = e^5 → 5 ✅

🧠 Mental Models

  • Exponentiation: “start small → get big”

  • Logarithm: “start big → see how many steps back to base”

  • Logs turn multiplication into addition

  • Logs turn exponentiation into multiplication


🧠 87 Math Equations Every Programmer Should Know


1️⃣ Arithmetic Series Sum

$$\frac{n(n+1)}{2}$$

Input → Output

  • n=5 → 15
  • n=10 → 55
n = 10
result = n * (n + 1) // 2
print(result)

2️⃣ Sum of Range [a..b]

$$\frac{(a+b)(b-a+1)}{2}$$

Input → Output

  • a=3, b=7 → 25
a, b = 3, 7
result = (a + b) * (b - a + 1) // 2
print(result)

3️⃣ Difference of Two Numbers

$$|a-b|$$

Input → Output

  • a=10, b=3 → 7
a, b = 10, 3
print(a-b if a>b else b-a)

4️⃣ Mean (Average)

$$\frac{\sum x}{n}$$

Input → Output

  • [2,4,6] → 4
nums = [2,4,6]
print(sum(nums)//len(nums))

5️⃣ Weighted Average

$$\frac{\sum w_ix_i}{\sum w_i}$$

Input → Output

  • scores=[80,90], weights=[2,3] → 86
scores = [80,90]
weights = [2,3]
total = 0
w_sum = 0
for i in range(len(scores)):
    total += scores[i] * weights[i]
    w_sum += weights[i]
print(total // w_sum)

6️⃣ Modulo

$$a \bmod b$$

Input → Output

  • 17 mod 5 → 2
print(17 % 5)

7️⃣ Even / Odd Check

$$n \bmod 2$$

Input → Output

  • 7 → odd
n = 7
print("odd" if n % 2 else "even")

8️⃣ Square

$$n^2$$

Input → Output

  • 6 → 36
n = 6
print(n*n)

9️⃣ Cube

$$n^3$$

Input → Output

  • 3 → 27
n = 3
print(n*n*n)

🔟 Power (Exponentiation)

$$a^b$$

Input → Output

  • 2^5 → 32
a, b = 2, 5
result = 1
for _ in range(b):
    result *= a
print(result)

1️⃣1️⃣ Factorial

$$n!$$

Input → Output

  • 5 → 120
n = 5
fact = 1
for i in range(1, n+1):
    fact *= i
print(fact)

1️⃣2️⃣ Permutations

$$P(n,k)=\frac{n!}{(n-k)!}$$

Input → Output

  • n=5, k=2 → 20
n, k = 5, 2
res = 1
for i in range(n, n-k, -1):
    res *= i
print(res)

1️⃣3️⃣ Combinations

$$C(n,k)=\frac{n!}{k!(n-k)!}$$

Input → Output

  • n=5, k=2 → 10
n, k = 5, 2
num = 1
den = 1
for i in range(k):
    num *= (n-i)
    den *= (i+1)
print(num//den)

1️⃣4️⃣ Fibonacci Sequence

$$F_n = F_{n-1}+F_{n-2}$$

Input → Output

  • n=7 → 13
n = 7
a, b = 0, 1
for _ in range(n):
    a, b = b, a+b
print(a)

1️⃣5️⃣ Prefix Sum

$$P[i]=P[i-1]+a[i]$$

Input → Output

  • [1,2,3,4] → [0,1,3,6,10]
arr = [1,2,3,4]
prefix = [0]
for x in arr:
    prefix.append(prefix[-1] + x)
print(prefix)

1️⃣6️⃣ Sliding Window Sum

$$S_{i+1}=S_i-a_i+a_{i+k}$$

arr = [1,2,3,4,5]
k = 3
s = sum(arr[:k])
print(s)
for i in range(len(arr)-k):
    s = s - arr[i] + arr[i+k]
    print(s)

1️⃣7️⃣ XOR Property

$$a\oplus a = 0$$

Input → Output

  • [1,2,2,3,3] → 1
nums = [1,2,2,3,3]
x = 0
for n in nums:
    x ^= n
print(x)

1️⃣8️⃣ Binary Representation

$$\sum b_i2^i$$

n = 13
binary = ""
while n:
    binary = str(n%2) + binary
    n //= 2
print(binary)

1️⃣9️⃣ Pythagorean Theorem

$$a^2+b^2=c^2$$

a, b = 3, 4
c = (a*a + b*b)**0.5
print(c)

2️⃣0️⃣ Euclidean Distance (2D)

$$\sqrt{(x1-x2)^2+(y1-y2)^2}$$

x1,y1,x2,y2 = 1,1,4,5
d = ((x1-x2)**2 + (y1-y2)**2)**0.5
print(d)

2️⃣1️⃣ Manhattan Distance

$$|x1-x2|+|y1-y2|$$

print(abs(1-4) + abs(1-5))

2️⃣2️⃣ Min–Max Normalization

$$\frac{x-min}{max-min}$$

x, mn, mx = 75, 50, 100
print((x-mn)/(mx-mn))

2️⃣3️⃣ Probability

$$P=\frac{favorable}{total}$$

print(1/6)

2️⃣4️⃣ Expected Value

$$E(X)=\sum xP(x)$$

values = [0,1]
probs = [0.7,0.3]
ev = 0
for i in range(2):
    ev += values[i]*probs[i]
print(ev)

2️⃣5️⃣ Log Base 2 (Loop Count)

$$2^k = n$$

n = 16
k = 0
while n > 1:
    n //= 2
    k += 1
print(k)

2️⃣6️⃣ Big-O (n²)

count = 0
n = 5
for i in range(n):
    for j in range(n):
        count += 1
print(count)

2️⃣7️⃣ Recurrence Relation

$$T(n)=T(n-1)+1$$

def T(n):
    if n==0: return 0
    return T(n-1)+1
print(T(5))

2️⃣8️⃣ Gradient Idea (Slope)

$$\frac{\Delta y}{\Delta x}$$

x1,y1 = 1,2
x2,y2 = 4,8
print((y2-y1)/(x2-x1))

2️⃣9️⃣ Linear Equation

$$y=ax+b$$

a,b,x = 2,3,5
print(a*x+b)

3️⃣0️⃣ State Transition

$$S_{t+1}=f(S_t)$$

state = 1
for _ in range(5):
    state = state * 2
print(state)

3️⃣1️⃣ Ratio

$$a:b$$

a,b = 2,5
print(a/(a+b), b/(a+b))

3️⃣2️⃣ Percentage

$$\frac{part}{whole}$$

print(30/200*100)

3️⃣3️⃣ Ceiling Division

$$\lceil a/b \rceil$$

a,b = 10,3
print((a+b-1)//b)

3️⃣4️⃣ GCD (Euclidean Algorithm)

a,b = 48,18
while b:
    a,b = b, a%b
print(a)

3️⃣5️⃣ LCM

a,b = 4,6
g = a
c = b
while c:
    g,c = c, g%c
print(a*b//g)

3️⃣6️⃣ Prime Check

n = 29
is_prime = True
for i in range(2, n):
    if n % i == 0:
        is_prime = False
print(is_prime)

3️⃣7️⃣ Count Digits

n = 12345
count = 0
while n:
    n //= 10
    count += 1
print(count)

3️⃣8️⃣ Reverse Number

n = 1234
rev = 0
while n:
    rev = rev*10 + n%10
    n //= 10
print(rev)

3️⃣9️⃣ Palindrome Check

s = "racecar"
print(s == s[::-1])

4️⃣0️⃣ Sum of Digits

n = 123
s = 0
while n:
    s += n%10
    n //= 10
print(s)

4️⃣1️⃣ Binary Search Steps

arr = [1,3,5,7,9]
target = 7
l,r = 0,len(arr)-1
steps = 0
while l<=r:
    m = (l+r)//2
    steps += 1
    if arr[m]==target: break
    elif arr[m]<target: l=m+1
    else: r=m-1
print(steps)

4️⃣2️⃣ Graph Degree Count

edges = [(1,2),(2,3),(2,4)]
degree = {}
for u,v in edges:
    degree[u] = degree.get(u,0)+1
    degree[v] = degree.get(v,0)+1
print(degree)

4️⃣3️⃣ BFS Node Count

graph = {1:[2,3],2:[4],3:[],4:[]}
queue = [1]
visited = set()
count = 0
while queue:
    node = queue.pop(0)
    if node in visited: continue
    visited.add(node)
    count += 1
    queue += graph[node]
print(count)

4️⃣4️⃣ DFS Depth

def dfs(node, depth):
    if node is None: return depth
    return dfs(None, depth+1)
print(dfs(1,0))

4️⃣5️⃣ Entropy (Binary)

p = 0.5
entropy = -p*(p**0.0) - p*(p**0.0)
print(entropy)

4️⃣6️⃣ Loss (Squared Error)

y, y_hat = 10, 7
print((y-y_hat)**2)

4️⃣7️⃣ Sigmoid (Manual)

x = 0
print(1/(1+2.71828**(-x)))

4️⃣8️⃣ Softmax (2 values)

a,b = 2,1
ea = 2.71828**a
eb = 2.71828**b
print(ea/(ea+eb), eb/(ea+eb))

4️⃣9️⃣ Monte Carlo Average

import random
s = 0
n = 1000
for _ in range(n):
    s += 1
print(s/n)

5️⃣0️⃣ Law of Large Numbers

s = 0
n = 10000
for i in range(1,n+1):
    s += i
print(s/n)

5️⃣1️⃣ Arithmetic Progression (General)

$$a_n = a_1 + (n-1)d$$

Input → Output

  • a₁=2, d=3, n=5 → 14
a1, d, n = 2, 3, 5
print(a1 + (n-1)*d)

Helps solve:

  • Sequence prediction
  • Index-based patterns

Builds intuition:

Position matters as much as value.


5️⃣2️⃣ Geometric Progression Term

$$a_n = a_1 r^{n-1}$$

a1, r, n = 3, 2, 4
print(a1 * (r**(n-1)))

Helps solve:

  • Explosive growth
  • Recursive structures

5️⃣3️⃣ Sum of Geometric Progression

$$S_n = a \frac{r^n-1}{r-1}$$

a, r, n = 1, 2, 5
print(a*(r**n-1)//(r-1))

Helps solve:

  • Infinite-like growth
  • Algorithm bounds

5️⃣4️⃣ Inclusion–Exclusion Principle

$$|A∪B| = |A|+|B|-|A∩B|$$

A = {1,2,3}
B = {3,4}
print(len(A)+len(B)-len(A&B))

Helps solve:

  • Counting overlaps
  • Probability traps

5️⃣5️⃣ GCD Property

$$gcd(a,b)=gcd(b,a\bmod b)$$

a,b = 1071,462
while b:
    a,b = b,a%b
print(a)

Helps solve:

  • Number theory
  • Periodicity

5️⃣6️⃣ Modular Addition

$$(a+b)\bmod m$$

a,b,m = 17,29,5
print((a+b)%m)

Helps solve:

  • Large number safety

5️⃣7️⃣ Modular Multiplication

$$(a·b)\bmod m$$

print((123*456)%7)

Helps solve:

  • Cryptography basics

5️⃣8️⃣ Modular Exponentiation

$$a^b \bmod m$$

a,b,m = 3,13,7
res = 1
for _ in range(b):
    res = (res*a)%m
print(res)

Helps solve:

  • Secure computation

5️⃣9️⃣ Fermat’s Little Theorem

$$a^{p-1}≡1 \pmod p$$

a,p = 3,7
print((a**(p-1))%p)

Helps solve:

  • Fast inverse mod

6️⃣0️⃣ Modular Inverse (Prime)

$$a^{p-2} \bmod p$$

a,p = 3,7
print((a**(p-2))%p)

6️⃣1️⃣ Chinese Remainder (2 eq)

$$x≡a (m), x≡b (n)$$

# brute for demo
for x in range(1,50):
    if x%3==2 and x%5==3:
        print(x)
        break

6️⃣2️⃣ Pigeonhole Principle

$$n+1 items → n boxes$$

items, boxes = 11,10
print(items>boxes)

6️⃣3️⃣ Prime Counting Intuition

$$\pi(n)$$

n=20
primes=[]
for i in range(2,n+1):
    ok=True
    for j in range(2,i):
        if i%j==0: ok=False
    if ok: primes.append(i)
print(len(primes))

6️⃣4️⃣ Perfect Square Check

$$k^2=n$$

n=49
print(int(n**0.5)**2==n)

6️⃣5️⃣ Divisor Counting

$$n=∏p_i^{e_i} → ∏(e_i+1)$$

n=36
count=0
for i in range(1,n+1):
    if n%i==0: count+=1
print(count)

6️⃣6️⃣ Sum of Divisors

n=12
s=0
for i in range(1,n+1):
    if n%i==0: s+=i
print(s)

6️⃣7️⃣ Euler Totient (φ)

n=9
count=0
for i in range(1,n+1):
    if __import__('math').gcd(i,n)==1:
        count+=1
print(count)

6️⃣8️⃣ Binomial Theorem

$$(a+b)^n$$

a,b,n = 1,2,3
print((a+b)**n)

6️⃣9️⃣ Pascal Triangle Rule

$$C(n,k)=C(n-1,k-1)+C(n-1,k)$$

C=[[1]]
for i in range(1,5):
    row=[1]
    for j in range(1,i):
        row.append(C[i-1][j-1]+C[i-1][j])
    row.append(1)
    C.append(row)
print(C)

7️⃣0️⃣ Catalan Numbers

$$C_n = \frac{1}{n+1}{2n \choose n}$$

n=4
num=1
den=1
for i in range(n):
    num*=2*n-i
    den*=i+1
print(num//den//(n+1))

7️⃣1️⃣ Principle of Mathematical Induction

# verify sum 1..n = n(n+1)/2
for n in range(1,10):
    if sum(range(1,n+1))!=n*(n+1)//2:
        print(False)
print(True)

7️⃣2️⃣ Invariant Concept

# parity invariant
nums=[1,3,5]
print(sum(nums)%2)

7️⃣3️⃣ Symmetry

arr=[1,2,3,2,1]
print(arr==arr[::-1])

7️⃣4️⃣ Extremal Principle

arr=[3,7,2,9,4]
print(max(arr), min(arr))

7️⃣5️⃣ Greedy Choice Property

coins=[5,2,1]
amount=11
cnt=0
for c in coins:
    cnt+=amount//c
    amount%=c
print(cnt)

7️⃣6️⃣ AM ≥ GM

$$\frac{a+b}{2} ≥ \sqrt{ab}$$

a,b=4,9
print((a+b)/2 >= (a*b)**0.5)

7️⃣7️⃣ Cauchy–Schwarz (Vector Intuition)

a=[1,2]
b=[3,4]
dot= a[0]*b[0]+a[1]*b[1]
print(dot)

7️⃣8️⃣ Triangle Inequality

a,b,c=3,4,8
print(a+b>c)

7️⃣9️⃣ Counting Paths (Grid)

$$C(m+n,m)$$

m,n=2,3
num=1
den=1
for i in range(m):
    num*=m+n-i
    den*=i+1
print(num//den)

8️⃣0️⃣ Matrix Power (Transition)

# Fibonacci via transition idea
n=5
a,b=0,1
for _ in range(n):
    a,b=b,a+b
print(a)

8️⃣1️⃣ Recursion Tree Size

def f(n):
    if n==0: return 1
    return f(n-1)+f(n-1)
print(f(4))

8️⃣2️⃣ Probability Complement

$$P(A^c)=1-P(A)$$

p=0.3
print(1-p)

8️⃣3️⃣ Expected Steps

steps=[1,2,3]
probs=[0.2,0.3,0.5]
print(sum(steps[i]*probs[i] for i in range(3)))

8️⃣4️⃣ Random Walk Expectation

pos=0
for _ in range(1000): pos+=1
print(pos/1000)

8️⃣5️⃣ Variance Identity

xs=[1,2,3]
mean=sum(xs)/len(xs)
var=sum((x-mean)**2 for x in xs)/len(xs)
print(var)

8️⃣6️⃣ Chebyshev Intuition

# bound idea
print("few values far from mean")

8️⃣7️⃣ Graph Handshaking Lemma

edges=[(1,2),(2,3)]
deg={}
for u,v in edges:
    deg[u]=deg.get(u,0)+1
    deg[v]=deg.get(v,0)+1
print(sum(deg.values())==2*len(edges))

🏁 Final Thought

Mathematics is not about formulas. It is about confidence in thinking.

If you understand these 50 ideas, you are no longer just writing code.

You are designing systems.


Next