Classic algorithms · 3 / 22 Theory

Number algorithms: Euclid and the sieve

Numbers also have their classic algorithms, some of them more than 2000 years old.

Greatest common divisor: the Euclidean algorithm

The GCD of two numbers is the largest number that divides both. Euclid noticed that GCD(a, b) equals GCD(b, a % b), and that when the remainder is 0 we are done:

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

print(gcd(48, 18))   # 6
print(gcd(17, 5))    # 1
print(gcd(1071, 462))  # 21

Let us follow the calculation of gcd(48, 18):

aba % b
481812
18126
1260
60—

It is much faster than trying all the divisors. Python has it built in as math.gcd:

import math

print(math.gcd(48, 18))  # 6

Prime numbers: trial division

A number is prime if it is only divisible by 1 and by itself. It is enough to try divisors up to its square root:

def is_prime(n):
    if n < 2:
        return False
    i = 2
    while i * i <= n:
        if n % i == 0:
            return False
        i += 1
    return True

print([n for n in range(20) if is_prime(n)])
# [2, 3, 5, 7, 11, 13, 17, 19]

Sieve of Eratosthenes

To get all the primes up to n, there is a much more efficient method: write down all the numbers, and for each prime cross out its multiples. What is not crossed out is prime:

n = 30

is_prime = [True] * (n + 1)
is_prime[0] = False
is_prime[1] = False

i = 2
while i * i <= n:
    if is_prime[i]:
        for m in range(i * i, n + 1, i):
            is_prime[m] = False
    i += 1

print([k for k in range(n + 1) if is_prime[k]])
# [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

Crossing out starts at i * i because the smaller multiples of i were already crossed out by an earlier prime.

Practice with Greatest common divisor and Sieve of Eratosthenes.