Number-Theoretic Algorithms

Number theory is about numbers, especially whole numbers. In computer science, we use number-theoretic algorithms for things like cryptography, hashing, and puzzles.

1. GCD – Greatest Common Divisor

The GCD of two numbers is the biggest number that divides both.

Example: GCD of 12 and 18 is 6.

Why is GCD useful?

It helps in simplifying fractions. It’s also used in cryptography and modular math.

Euclidean Algorithm

This is a fast way to find GCD.

Idea: Keep replacing the bigger number with the remainder of the two.

Example: GCD(18, 12)

Python Code

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

2. Modular Arithmetic

Modular means "clock math." After a fixed number, we start again from 0.

Example: 5 + 9 mod 12 = 2 (like hours on a clock)

Common use: Keeping numbers small. For example, in cryptography, we work mod 109+7.

Properties

3. Fast Exponentiation

What is 3100? That’s huge! But we can compute it fast using exponentiation by squaring.

Why is this useful?

Used in RSA encryption and many math problems.

Idea

Python Code

def fast_exp(a, n, m):
  result = 1
  a = a % m
  while n > 0:
    if n % 2 == 1:
      result = (result * a) % m
    a = (a * a) % m
    n = n // 2
  return result

Example

210 mod 1000 = 24

4. Primality Testing

A prime number has only 2 divisors: 1 and itself.

Simple Method

Check all numbers from 2 to √n.

Python Code

def is_prime(n):
  if n <= 1:
    return False
  for i in range(2, int(n ** 0.5) + 1):
    if n % i == 0:
      return False
  return True

Daily Life Example

Imagine you want to divide a group of candies equally. If you can’t, maybe the number of candies is prime!

5. Modular Inverse

Modular inverse of a is a number b such that (a × b) % m = 1.

It’s like division in mod world.

Use Case

Needed when solving equations with mod.

How to find it?

Use Extended Euclidean Algorithm or Fermat’s Little Theorem.

Python Code using Fermat’s Theorem

When m is prime:

def mod_inverse(a, m):
  return fast_exp(a, m-2, m)

6. Applications in Real Life

Summary

Fun Fact

Some prime numbers are used to protect your passwords online. Number theory is not just theory — it keeps you safe!