Skip to content
The site is in test mode. All features are free for now.
MathAgora

C++ and Mathematics

Number theory in code

The Euclidean algorithm, GCD and LCM, primes, divisors, digits and modular arithmetic.

60 min 8 questions

01The Euclidean algorithm

Key fact: gcd⁡(a,b)=gcd⁡(b,a mod b)\gcd(a, b) = \gcd(b, a \bmod b) and gcd⁡(a,0)=a\gcd(a, 0) = a. The numbers shrink quickly, so the algorithm takes O(log⁡min⁡(a,b))O(\log\min(a,b)) steps; the "slowest" case is two consecutive Fibonacci numbers. LCM: lcm⁡(a,b)=agcd⁡(a,b)⋅b\operatorname{lcm}(a, b) = \frac{a}{\gcd(a, b)}\cdot b (divide first to avoid overflow).

C++
int gcd(int a, int b) {
    while (b != 0) {
        int t = a % b;
        a = b;
        b = t;
    }
    return a;
}

02Primes and divisors

n≥2n \ge 2 is prime if it has no divisor from 22 to n\sqrt n: if n=abn = ab with a≤ba \le b, then a≤na \le \sqrt n. In code we write the condition as i * i <= n to avoid floating-point roots.

For a whole range the Sieve of Eratosthenes is faster: for each prime pp, cross out its multiples.

C++
bool isPrime(int n) {
    if (n < 2) return false;
    for (int i = 2; i * i <= n; i++)
        if (n % i == 0) return false;
    return true;
}

03Modular arithmetic

(a⋅b) mod m=((a mod m)(b mod m)) mod m(a\cdot b) \bmod m = \big((a \bmod m)(b \bmod m)\big) \bmod m, so the remainder of a huge power can be computed by reducing at every step, so the numbers never grow. For example, 2100 mod 72^{100} \bmod 7 can be computed by a loop that only ever stores 0–6.

Key formulas

  • Euclidean algorithm

    gcd⁡(a,b)=gcd⁡(b, a mod b),gcd⁡(a,0)=a\gcd(a,b)=\gcd(b,\ a\bmod b),\quad \gcd(a,0)=a
  • LCM

    lcm⁡(a,b)=agcd⁡(a,b) b\operatorname{lcm}(a,b)=\dfrac{a}{\gcd(a,b)}\,b
  • Why checking up to n\sqrt n suffices

    n=ab, a≤b ⇒ a≤nn=ab,\ a\le b\ \Rightarrow\ a\le\sqrt n
  • Remainder of a product

    ab mod m=((a mod m)(b mod m)) mod mab\bmod m=\big((a\bmod m)(b\bmod m)\big)\bmod m

Worked examples

Example 1

Trace gcd(48, 18).

C++
(48, 18) -> (18, 12) -> (12, 6) -> (6, 0)  =>  6