Python 3D Academyবাংলা

GCD, LCM and primes with the sieve

🌍 In real life. Ammu has 24 rosogollas and 36 sandesh to pack into gift boxes, every box the same and nothing left over. The most boxes she can make is the greatest common divisor of 24 and 36, which is 12: each box gets 2 rosogollas and 3 sandesh. Two buses leave the terminal together, one every 12 minutes and one every 18; they leave together again after the least common multiple, 36 minutes.

The idea in one sentence: Euclid's rule gcd(a, b) = gcd(b, a % b) shrinks the numbers fast until the remainder is 0, lcm(a, b) = a × b // gcd(a, b), and the sieve of Eratosthenes finds every prime up to n by crossing out the multiples of each prime.

Its words:

  • divisor: d divides a when a % d == 0
  • gcd: the biggest number dividing both; lcm: the smallest number both divide
  • prime: a number above 1 whose only divisors are 1 and itself; 1 is not prime
  • sieve: a list of True/False, one per number, where crossing out means setting False

Euclid's rule, step by step:

  1. if b is 0, the answer is a
  2. otherwise replace (a, b) by (b, a % b) and repeat

For 1071 and 462: 1071 % 462 = 147, 462 % 147 = 21, 147 % 21 = 0, so the gcd is 21, in three steps.

The sieve, step by step:

  1. write the numbers from 2 to n, none crossed out
  2. the smallest number not crossed out is prime; cross out its multiples from p × p
  3. repeat while p × p is at most n; everything left is prime

Watch the sieve on 1 to 50:

Why Euclid's rule is right. If d divides a and b, it divides a − q × b for any q, and a % b is exactly such a number; the other way round, a divisor of b and a % b also divides a. So (a, b) and (b, a % b) have the same divisors, and the same greatest one. The remainder is smaller than b, so the numbers keep shrinking until b is 0.

Why the sieve may start at p × p. A multiple k × p with k smaller than p has a prime factor smaller than p, so a smaller prime has crossed it out already. And once p × p is past n, every number left has no factor up to its square root, so it is prime.

What it costs, by counting. Euclid's rule needs about as many steps as the numbers have digits, times a small constant: O(log n). The sieve does O(n log log n) crossings, almost one per number: for 1 to 100 it crosses 104 times, and for 1 to 1,000,000 about 2,122,000 times, against far more divisions if you tested each number on its own.

def gcd(a, b):
    while b:
        a, b = b, a % b       # what divides a and b also divides a % b
    return a

from math import gcd

def lcm_all(nums):
    result = 1
    for x in nums:
        result = result * x // gcd(result, x)   # lcm(a, b) = a * b // gcd(a, b)
    return result

def primes_up_to(n):
    if n < 2:
        return []
    is_prime = [True] * (n + 1)
    is_prime[0] = is_prime[1] = False
    p = 2
    while p * p <= n:
        if is_prime[p]:
            for m in range(p * p, n + 1, p):   # smaller multiples are already crossed
                is_prime[m] = False
        p += 1
    return [k for k in range(n + 1) if is_prime[k]]

print(gcd(24, 36), gcd(1071, 462))
print(lcm_all([12, 18]), lcm_all([4, 6, 8]))
print(primes_up_to(50))

Mistakes and edge cases.

  • 1 is not prime: set is_prime[1] = False, and return [] for n below 2
  • range(p * p, n) misses n itself: the stop is n + 1
  • gcd with a zero: gcd(a, 0) is a; Euclid's loop handles it because it checks b first
  • lcm as a × b: that is a common multiple, but not the least one: 12 × 18 is 216, not 36
  • Python's math.gcd does the same and is fine to use once you know how it works

Quiz

  1. What does this print?

    def gcd(a, b):
        while b:
            a, b = b, a % b       # what divides a and b also divides a % b
        return a
    
    print(gcd(48, 18))
  2. What does this print?

    from math import gcd
    
    def lcm_all(nums):
        result = 1
        for x in nums:
            result = result * x // gcd(result, x)   # lcm(a, b) = a * b // gcd(a, b)
        return result
    
    print(lcm_all([4, 6]))
  3. Why may the sieve start crossing at p × p?

    • Smaller multiples of p have a smaller prime factor that crossed them already
    • Smaller multiples of p are prime
    • It is only faster, and sometimes wrong
  4. What does this print?

    def primes_up_to(n):
        if n < 2:
            return []
        is_prime = [True] * (n + 1)
        is_prime[0] = is_prime[1] = False
        p = 2
        while p * p <= n:
            if is_prime[p]:
                for m in range(p * p, n + 1, p):   # smaller multiples are already crossed
                    is_prime[m] = False
            p += 1
        return [k for k in range(n + 1) if is_prime[k]]
    
    print(primes_up_to(20))
  5. primes_up_to(9) keeps 9 as a prime. Which line is wrong?

    def primes_up_to(n):
        if n < 2:
            return []
        is_prime = [True] * (n + 1)
        is_prime[0] = is_prime[1] = False
        p = 2
        while p * p <= n:
            if is_prime[p]:
                for m in range(p * p, n, p):
                    is_prime[m] = False
            p += 1
        return [k for k in range(n + 1) if is_prime[k]]

Coding tasks

  1. Write gcd(a, b) with Euclid's rule (without math.gcd): the greatest common divisor of two whole numbers that are not both 0.

  2. Write lcm_all(nums): buses leave together, bus i every nums[i] minutes. Return after how many minutes they all leave together again (the least common multiple). You may use math.gcd.

  3. Write primes_up_to(n): the list of all primes from 2 to n, using the sieve of Eratosthenes.