Number theory is about numbers, especially whole numbers. In computer science, we use number-theoretic algorithms for things like cryptography, hashing, and puzzles.
The GCD of two numbers is the biggest number that divides both.
Example: GCD of 12 and 18 is 6.
It helps in simplifying fractions. It’s also used in cryptography and modular math.
This is a fast way to find GCD.
Idea: Keep replacing the bigger number with the remainder of the two.
Example: GCD(18, 12)
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
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.
What is 3100? That’s huge! But we can compute it fast using exponentiation by squaring.
Used in RSA encryption and many math problems.
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
210 mod 1000 = 24
A prime number has only 2 divisors: 1 and itself.
Check all numbers from 2 to √n.
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
Imagine you want to divide a group of candies equally. If you can’t, maybe the number of candies is prime!
Modular inverse of a is a number b such that (a × b) % m = 1.
It’s like division in mod world.
Needed when solving equations with mod.
Use Extended Euclidean Algorithm or Fermat’s Little Theorem.
When m is prime:
def mod_inverse(a, m):
return fast_exp(a, m-2, m)
Some prime numbers are used to protect your passwords online. Number theory is not just theory — it keeps you safe!