Number theory studies integers, and many simple-looking questions are very hard: whether x³ + y³ + z³ = 33 has an integer solution was open for decades (one was found in 2019). In this chapter all numbers are integers.

A number a is a factor (divisor) of b, written a | b, if a divides b; the factors of 24 are 1, 2, 3, 4, 6, 8, 12, 24. A number n > 1 is a prime if its only positive factors are 1 and n. Every n > 1 has a unique prime factorization n = p1α1 ⋯ pkαk, for example 84 = 2² · 3 · 7.

  • the number of factors τ(n) = ∏ (αi + 1): τ(84) = 3 · 2 · 2 = 12;
  • the sum of factors σ(n) = ∏ (1 + pi + … + piαi) = ∏ (piαi+1 − 1)/(pi − 1): σ(84) = 7 · 4 · 8 = 224;
  • the product of factors nτ(n)/2, because the factors form τ(n)/2 pairs with product n: 846 = 351298031616;
  • n is a perfect number if n = σ(n) − n, like 28 = 1 + 2 + 4 + 7 + 14.

Primes

There are infinitely many primes: if p1, …, pn were all of them, p1⋯pn + 1 would have a prime factor outside the list. They are frequent: the number of primes up to n is π(n) ≈ n/ln n. Famous unproven conjectures: Goldbach (every even n > 2 is a sum of two primes), the twin primes (infinitely many pairs p, p + 2) and Legendre (there is always a prime between n² and (n + 1)²).

If n is not prime, n = a · b with a ≤ √n, so it has a factor between 2 and ⌊√n⌋. Hence both the primality test and the factorization take O(√n). The program reads a count and then the numbers:

#include <bits/stdc++.h>
using namespace std;

bool prime(long long n) {
    if (n < 2) return false;
    for (long long x = 2; x * x <= n; x++) {
        if (n % x == 0) return false;
    }
    return true;
}

vector<long long> factors(long long n) {  // the prime factorization, e.g. 24 -> [2, 2, 2, 3]
    vector<long long> f;
    for (long long x = 2; x * x <= n; x++) {
        while (n % x == 0) {
            f.push_back(x);
            n /= x;
        }
    }
    if (n > 1) f.push_back(n);
    return f;
}

int main() {
    int q;
    cin >> q;
    while (q--) {
        long long n;
        cin >> n;
        vector<long long> f = factors(n);
        cout << n << (prime(n) ? " is prime" : " is not prime") << ", factors:";
        for (long long p : f) cout << " " << p;
        // group equal primes: n = p1^a1 * p2^a2 * ...
        long long tau = 1, sigma = 1;
        for (size_t i = 0; i < f.size();) {
            size_t j = i;
            long long pk = 1, s = 1;
            while (j < f.size() && f[j] == f[i]) {
                pk *= f[i];
                s += pk;  // 1 + p + … + p^a
                j++;
            }
            tau *= (j - i + 1);
            sigma *= s;
            i = j;
        }
        cout << "\n  tau = " << tau << ", sigma = " << sigma;
        if (tau % 2 == 0) {
            long long mu = 1;  // n^(tau/2), small enough here
            for (int i = 0; i < tau / 2; i++) mu *= n;
            cout << ", product of factors = " << mu;
        }
        if (sigma - n == n) cout << ", a perfect number";
        cout << "\n";
    }
}
4
84
28
24
41
Output
84 is not prime, factors: 2 2 3 7
  tau = 12, sigma = 224, product of factors = 351298031616
28 is not prime, factors: 2 2 7
  tau = 6, sigma = 56, product of factors = 21952, a perfect number
24 is not prime, factors: 2 2 2 3
  tau = 8, sigma = 60, product of factors = 331776
41 is prime, factors: 41
  tau = 2, sigma = 42, product of factors = 41

Sieve of Eratosthenes

The sieve of Eratosthenes builds an array: sieve[k] = 0 means that k is prime, otherwise sieve[k] is a prime factor of k. Go through 2…n; whenever a new prime x is found, mark its multiples 2x, 3x, … The inner loop runs n/x times, so the time is at most the harmonic sum n/2 + n/3 + … = O(n log n); since it runs only for primes, it is in fact O(n log log n).

#include <bits/stdc++.h>
using namespace std;

int main() {
    int n;
    cin >> n;
    vector<int> sieve(n + 1, 0);  // 0 = prime, otherwise a prime factor
    for (int x = 2; x <= n; x++) {
        if (sieve[x]) continue;
        for (int u = 2 * x; u <= n; u += x) {
            sieve[u] = x;
        }
    }
    int count = 0;
    for (int k = 2; k <= n; k++) if (!sieve[k]) count++;
    if (n <= 30) {
        for (int k = 2; k <= n; k++) cout << k << ":" << sieve[k] << " ";
        cout << "\n";
    }
    cout << "pi(" << n << ") = " << count << ", n / ln n = " << fixed << setprecision(0) << n / log(n) << "\n";
}
20
Output
2:0 3:0 4:2 5:0 6:3 7:0 8:2 9:3 10:5 11:0 12:3 13:0 14:7 15:5 16:2 17:0 18:3 19:0 20:5 
pi(20) = 8, n / ln n = 7
#include <bits/stdc++.h>
using namespace std;

int main() {
    int n;
    cin >> n;
    vector<int> sieve(n + 1, 0);  // 0 = prime, otherwise a prime factor
    for (int x = 2; x <= n; x++) {
        if (sieve[x]) continue;
        for (int u = 2 * x; u <= n; u += x) {
            sieve[u] = x;
        }
    }
    int count = 0;
    for (int k = 2; k <= n; k++) if (!sieve[k]) count++;
    if (n <= 30) {
        for (int k = 2; k <= n; k++) cout << k << ":" << sieve[k] << " ";
        cout << "\n";
    }
    cout << "pi(" << n << ") = " << count << ", n / ln n = " << fixed << setprecision(0) << n / log(n) << "\n";
}
1000000
Output
pi(1000000) = 78498, n / ln n = 72382
#include <bits/stdc++.h>
using namespace std;

int main() {
    int n;
    cin >> n;
    vector<int> sieve(n + 1, 0);
    for (int x = 2; x <= n; x++) {
        if (sieve[x] == 0) {
            for (int u = 2 * x; u <= n; u += x) sieve[u] = x;
        }
    }
    for (int k = 2; k <= n; k++) cout << sieve[k] << " ";
    cout << "\n";
}
20

Sieve of Eratosthenes

Euclid's algorithm

gcd(a, b) is the greatest number that divides both and lcm(a, b) the smallest number divisible by both; lcm(a, b) = ab/gcd(a, b). Euclid's algorithm (about 300 BC, perhaps the oldest known algorithm) uses gcd(a, 0) = a and gcd(a, b) = gcd(b, a mod b). It takes O(log n) steps; the worst case is two consecutive Fibonacci numbers.

Numbers are coprime if their gcd is 1. Euler's totient φ(n) counts the numbers 1…n coprime to n: φ(n) = ∏ piαi−1(pi − 1), for example φ(12) = 2 · 1 · 1 · 2 = 4, and φ(n) = n − 1 for a prime. The program prints the gcd chains for the pairs and then φ of the last number:

#include <bits/stdc++.h>
using namespace std;

long long gcd(long long a, long long b) {
    cout << "gcd(" << a << ", " << b << ")" << (b ? " = " : "");
    if (b == 0) return a;
    return gcd(b, a % b);
}

long long phi(long long n) {  // Euler's totient from the factorization
    long long r = 1;
    for (long long p = 2; p * p <= n; p++) {
        if (n % p) continue;
        long long pk = 1;
        while (n % p == 0) {
            n /= p;
            pk *= p;
        }
        r *= pk / p * (p - 1);  // p^(a-1) * (p - 1)
    }
    if (n > 1) r *= n - 1;
    return r;
}

int main() {
    int q;
    cin >> q;
    while (q--) {
        long long a, b;
        cin >> a >> b;
        long long g = gcd(a, b);
        cout << " -> " << g << ", lcm = " << a / g * b << "\n";
    }
    long long n;
    cin >> n;
    cout << "phi(" << n << ") = " << phi(n) << ":";
    for (long long k = 1; k <= n; k++) if (__gcd(k, n) == 1) cout << " " << k;
    cout << "\n";
}
2
24 36
13 8
12
Output
gcd(24, 36) = gcd(36, 24) = gcd(24, 12) = gcd(12, 0) -> 12, lcm = 72
gcd(13, 8) = gcd(8, 5) = gcd(5, 3) = gcd(3, 2) = gcd(2, 1) = gcd(1, 0) -> 1, lcm = 104
phi(12) = 4: 1 5 7 11

Based on: Antti Laaksonen, Competitive Programmer's Handbook, section 21.1 (CC BY-NC-SA 4.0). Changed: the text is shortened and adapted, the code fragments are complete programs, and the diagrams, tasks and quizzes are new. Adaptation: Boban Blagojević, CC BY-NC-SA 4.0.