Post · 13 min read· pp. 46–54

Integer factorization

In this article we list several algorithms for the factorization of integers, each of which can be either fast or varying levels of slow depending on their input.

Notice, if the number that you want to factorize is actually a prime number, most of the algorithms will run very slowly. This is especially true for Fermat's, Pollard's p-1 and Pollard's rho factorization algorithms. Therefore, it makes the most sense to perform a probabilistic (or a fast deterministic) primality test before trying to factorize the number.

Trial division

This is the most basic algorithm to find a prime factorization.

We divide by each possible divisor dd. It can be observed that it is impossible for all prime factors of a composite number nn to be bigger than n\sqrt{n}. Therefore, we only need to test the divisors 2≤d≤n2 \le d \le \sqrt{n}, which gives us the prime factorization in O(n)O(\sqrt{n}). (This is pseudo-polynomial time, i.e. polynomial in the value of the input but exponential in the number of bits of the input.)

The smallest divisor must be a prime number. We remove the factored number, and continue the process. If we cannot find any divisor in the range [2;n][2; \sqrt{n}], then the number itself has to be prime.

text
vector<long long> trial_division1(long long n) {
    vector<long long> factorization;
    for (long long d = 2; d * d <= n; d++) {
        while (n % d == 0) {
            factorization.push_back(d);
            n /= d;
        }
    }
    if (n > 1)
        factorization.push_back(n);
    return factorization;
}

Wheel factorization

This is an optimization of the trial division. Once we know that the number is not divisible by 2, we don't need to check other even numbers. This leaves us with only 50%50\% of the numbers to check. After factoring out 2, and getting an odd number, we can simply start with 3 and only count other odd numbers.

text
vector<long long> trial_division2(long long n) {
    vector<long long> factorization;
    while (n % 2 == 0) {
        factorization.push_back(2);
        n /= 2;
    }
    for (long long d = 3; d * d <= n; d += 2) {
        while (n % d == 0) {
            factorization.push_back(d);
            n /= d;
        }
    }
    if (n > 1)
        factorization.push_back(n);
    return factorization;
}

This method can be extended further. If the number is not divisible by 3, we can also ignore all other multiples of 3 in the future computations. So we only need to check the numbers 5,7,11,13,17,19,23,…5, 7, 11, 13, 17, 19, 23, \dots. We can observe a pattern of these remaining numbers. We need to check all numbers with d mod 6=1d \bmod 6 = 1 and d mod 6=5d \bmod 6 = 5. So this leaves us with only 33.3%33.3\% percent of the numbers to check. We can implement this by factoring out the primes 2 and 3 first, after which we start with 5 and only count remainders 11 and 55 modulo 66.

Here is an implementation for the prime number 2, 3 and 5. It is convenient to store the skipping strides in an array.

text
vector<long long> trial_division3(long long n) {
    vector<long long> factorization;
    for (int d : {2, 3, 5}) {
        while (n % d == 0) {
            factorization.push_back(d);
            n /= d;
        }
    }
    static array<int, 8> increments = {4, 2, 4, 2, 4, 6, 2, 6};
    int i = 0;
    for (long long d = 7; d * d <= n; d += increments[i++]) {
        while (n % d == 0) {
            factorization.push_back(d);
            n /= d;
        }
        if (i == 8)
            i = 0;
    }
    if (n > 1)
        factorization.push_back(n);
    return factorization;
}

If we continue exending this method to include even more primes, better percentages can be reached, but the skip lists will become larger.

Precomputed primes

Extending the wheel factorization method indefinitely, we will only be left with prime numbers to check. A good way of checking this is to precompute all prime numbers with the Sieve of Eratosthenes until n\sqrt{n}, and test them individually.

text
vector<long long> primes;

vector<long long> trial_division4(long long n) {
    vector<long long> factorization;
    for (long long d : primes) {
        if (d * d > n)
            break;
        while (n % d == 0) {
            factorization.push_back(d);
            n /= d;
        }
    }
    if (n > 1)
        factorization.push_back(n);
    return factorization;
}

Fermat's factorization method

We can write an odd composite number n=p⋅qn = p \cdot q as the difference of two squares n=a2−b2n = a^2 - b^2:

n=(p+q2)2−(p−q2)2n = \left(\frac{p + q}{2}\right)^2 - \left(\frac{p - q}{2}\right)^2

Fermat's factorization method tries to exploit this fact by guessing the first square a2a^2, and checking if the remaining part, b2=a2−nb^2 = a^2 - n, is also a square number. If it is, then we have found the factors a−ba - b and a+ba + b of nn.

text
int fermat(int n) {
    int a = ceil(sqrt(n));
    int b2 = a*a - n;
    int b = round(sqrt(b2));
    while (b * b != b2) {
        a = a + 1;
        b2 = a*a - n;
        b = round(sqrt(b2));
    }
    return a - b;
}

This factorization method can be very fast if the difference between the two factors pp and qq is small. The algorithm runs in O(∣p−q∣)O(|p - q|) time. In practice though, this method is rarely used. Once factors become further apart, it is extremely slow.

However, there are still a large number of optimization options regarding this approach. By looking at the squares a2a^2 modulo a fixed small number, it can be observed that certain values aa don't have to be viewed, since they cannot produce a square number a2−na^2 - n.

Pollard's p−1p - 1 method

It is very likely that a number nn has at least one prime factor pp such that p−1p - 1 is B\mathrm{B}-powersmooth for small B\mathrm{B}. An integer mm is said to be B\mathrm{B}-powersmooth if every prime power dividing mm is at most B\mathrm{B}. Formally, let B⩾1\mathrm{B} \geqslant 1 and let mm be any positive integer. Suppose the prime factorization of mm is m=∏qieim = \prod {q_i}^{e_i}, where each qiq_i is a prime and ei⩾1e_i \geqslant 1. Then mm is B\mathrm{B}-powersmooth if, for all ii, qiei⩽B{q_i}^{e_i} \leqslant \mathrm{B}. E.g. the prime factorization of 48171914817191 is 1303⋅36971303 \cdot 3697. And the values, 1303−11303 - 1 and 3697−13697 - 1, are 3131-powersmooth and 1616-powersmooth respectively, because 1303−1=2⋅3⋅7⋅311303 - 1 = 2 \cdot 3 \cdot 7 \cdot 31 and 3697−1=24⋅3⋅7⋅113697 - 1 = 2^4 \cdot 3 \cdot 7 \cdot 11. In 1974 John Pollard invented a method to extract factors pp, s.t. p−1p-1 is B\mathrm{B}-powersmooth, from a composite number.

The idea comes from Fermat's little theorem. Let a factorization of nn be n=p⋅qn = p \cdot q. It says that if aa is coprime to pp, the following statement holds:

ap−1≡1(modp)a^{p - 1} \equiv 1 \pmod{p}

This also means that

(a(p−1))k≡ak⋅(p−1)≡1(modp).{\left(a^{(p - 1)}\right)}^k \equiv a^{k \cdot (p - 1)} \equiv 1 \pmod{p}.

So for any MM with p−1 ∣ Mp - 1 ~|~ M we know that aM≡1a^M \equiv 1. This means that aM−1=p⋅ra^M - 1 = p \cdot r, and because of that also p ∣ gcd⁡(aM−1,n)p ~|~ \gcd(a^M - 1, n).

Therefore, if p−1p - 1 for a factor pp of nn divides MM, we can extract a factor using Euclid's algorithm.

It is clear, that the smallest MM that is a multiple of every B\mathrm{B}-powersmooth number is lcm(1, 2 ,3 ,4 , …, B)\text{lcm}(1,~2~,3~,4~,~\dots,~B). Or alternatively:

M=∏prime q≤Bq⌊log⁡qB⌋M = \prod_{\text{prime } q \le B} q^{\lfloor \log_q B \rfloor}

Notice, if p−1p-1 divides MM for all prime factors pp of nn, then gcd⁡(aM−1,n)\gcd(a^M - 1, n) will just be nn. In this case we don't receive a factor. Therefore, we will try to perform the gcd⁡\gcd multiple times, while we compute MM.

Some composite numbers don't have factors pp s.t. p−1p-1 is B\mathrm{B}-powersmooth for small B\mathrm{B}. For example, for the composite number 100 000 000 000 000 493=763 013⋅131 059 365 961100~000~000~000~000~493 = 763~013 \cdot 131~059~365~961, values p−1p-1 are 190 753190~753-powersmooth and 1 092 161 3831~092~161~383-powersmooth correspondingly. We will have to choose B≥190 753B \geq 190~753 to factorize the number.

In the following implementation we start with B=10\mathrm{B} = 10 and increase B\mathrm{B} after each each iteration.

text
long long pollards_p_minus_1(long long n) {
    int B = 10;
    long long g = 1;
    while (B <= 1000000 && g < n) {
        long long a = 2 + rand() %  (n - 3);
        g = gcd(a, n);
        if (g > 1)
            return g;

        // compute a^M
        for (int p : primes) {
            if (p >= B)
                continue;
            long long p_power = 1;
            while (p_power * p <= B)
                p_power *= p;
            a = power(a, p_power, n);

            g = gcd(a - 1, n);
            if (g > 1 && g < n)
                return g;
        }
        B *= 2;
    }
    return 1;
}

Observe that this is a probabilistic algorithm. A consequence of this is that there is a possibility of the algorithm being unable to find a factor at all.

The complexity is O(Blog⁡Blog⁡2n)O(B \log B \log^2 n) per iteration.

Pollard's rho algorithm

Pollard's Rho Algorithm is yet another factorization algorithm from John Pollard.

Let the prime factorization of a number be n=pqn = p q. The algorithm looks at a pseudo-random sequence {xi}={x0, f(x0), f(f(x0)), … }\{x_i\} = \{x_0,~f(x_0),~f(f(x_0)),~\dots\} where ff is a polynomial function, usually f(x)=(x2+c) mod nf(x) = (x^2 + c) \bmod n is chosen with c=1c = 1.

In this instance, we are not interested in the sequence {xi}\{x_i\}. We are more interested in the sequence {xi mod p}\{x_i \bmod p\}. Since ff is a polynomial function, and all the values are in the range [0; p)[0;~p), this sequence will eventually converge into a loop. The birthday paradox actually suggests that the expected number of elements is O(p)O(\sqrt{p}) until the repetition starts. If pp is smaller than n\sqrt{n}, the repetition will likely start in O(n4)O(\sqrt[4]{n}).

Here is a visualization of such a sequence {xi mod p}\{x_i \bmod p\} with n=2206637n = 2206637, p=317p = 317, x0=2x_0 = 2 and f(x)=x2+1f(x) = x^2 + 1. From the form of the sequence you can see very clearly why the algorithm is called Pollard's ρ\rho algorithm.

Pollard's rho visualization

Yet, there is still an open question. How can we exploit the properties of the sequence {xi mod p}\{x_i \bmod p\} to our advantage without even knowing the number pp itself?

It's actually quite easy. There is a cycle in the sequence {xi mod p}i≤j\{x_i \bmod p\}_{i \le j} if and only if there are two indices s,t≤js, t \le j such that xs≡xt mod px_s \equiv x_t \bmod p. This equation can be rewritten as xs−xt≡0 mod px_s - x_t \equiv 0 \bmod p which is the same as p ∣ gcd⁡(xs−xt,n)p ~|~ \gcd(x_s - x_t, n).

Therefore, if we find two indices ss and tt with g=gcd⁡(xs−xt,n)>1g = \gcd(x_s - x_t, n) > 1, we have found a cycle and also a factor gg of nn. It is possible that g=ng = n. In this case we haven't found a proper factor, so we must repeat the algorithm with a different parameter (different starting value x0x_0, different constant cc in the polynomial function ff).

To find the cycle, we can use any common cycle detection algorithm.

Floyd's cycle-finding algorithm

This algorithm finds a cycle by using two pointers moving over the sequence at differing speeds. During each iteration, the first pointer will advance one element over, while the second pointer advances to every other element. Using this idea it is easy to observe that if there is a cycle, at some point the second pointer will come around to meet the first one during the loops. If the cycle length is λ\lambda and the μ\mu is the first index at which the cycle starts, then the algorithm will run in O(λ+μ)O(\lambda + \mu) time.

This algorithm is also known as the Tortoise and Hare algorithm, based on the tale in which a tortoise (the slow pointer) and a hare (the faster pointer) have a race.

It is actually possible to determine the parameter λ\lambda and μ\mu using this algorithm (also in O(λ+μ)O(\lambda + \mu) time and O(1)O(1) space). When a cycle is detected, the algorithm will return 'True'. If the sequence doesn't have a cycle, then the function will loop endlessly. However, using Pollard's Rho Algorithm, this can be prevented.

text
function floyd(f, x0):
    tortoise = x0
    hare = f(x0)
    while tortoise != hare:
        tortoise = f(tortoise)
        hare = f(f(hare))
    return true

Implementation

First, here is an implementation using the Floyd's cycle-finding algorithm. The algorithm generally runs in O(n4log⁡(n))O(\sqrt[4]{n} \log(n)) time.

text
long long mult(long long a, long long b, long long mod) {
    return (__int128)a * b % mod;
}

long long f(long long x, long long c, long long mod) {
    return (mult(x, x, mod) + c) % mod;
}

long long rho(long long n, long long x0=2, long long c=1) {
    long long x = x0;
    long long y = x0;
    long long g = 1;
    while (g == 1) {
        x = f(x, c, n);
        y = f(y, c, n);
        y = f(y, c, n);
        g = gcd(abs(x - y), n);
    }
    return g;
}

The following table shows the values of xx and yy during the algorithm for n=2206637n = 2206637, x0=2x_0 = 2 and c=1c = 1.

ixi mod nx2i mod nxi mod 317x2i mod 317gcd⁡(xi−x2i,n)02222−1526526122645833026265136771671573433214458330641379265881511664123519371696716167157312646823216917219308020884707474317\newcommand\T{\Rule{0pt}{1em}{.3em}} \begin{array}{|l|l|l|l|l|l|} \hline i & x_i \bmod n & x_{2i} \bmod n & x_i \bmod 317 & x_{2i} \bmod 317 & \gcd(x_i - x_{2i}, n) \\ \hline 0 & 2 & 2 & 2 & 2 & - \\ 1 & 5 & 26 & 5 & 26 & 1 \\ 2 & 26 & 458330 & 26 & 265 & 1 \\ 3 & 677 & 1671573 & 43 & 32 & 1 \\ 4 & 458330 & 641379 & 265 & 88 & 1 \\ 5 & 1166412 & 351937 & 169 & 67 & 1 \\ 6 & 1671573 & 1264682 & 32 & 169 & 1 \\ 7 & 2193080 & 2088470 & 74 & 74 & 317 \\ \hline \end{array}

The implementation uses a function mult, that multiplies two integers ≤1018\le 10^{18} without overflow by using a GCC's type __int128 for 128-bit integer. If GCC is not available, you can using a similar idea as binary exponentiation.

text
long long mult(long long a, long long b, long long mod) {
    long long result = 0;
    while (b) {
        if (b & 1)
            result = (result + a) % mod;
        a = (a + a) % mod;
        b >>= 1;
    }
    return result;
}

Alternatively you can also implement the Montgomery multiplication.

As stated previously, if nn is composite and the algorithm returns nn as factor, you have to repeat the procedure with different parameters x0x_0 and cc. E.g. the choice x0=c=1x_0 = c = 1 will not factor 25=5⋅525 = 5 \cdot 5. The algorithm will return 2525. However, the choice x0=1x_0 = 1, c=2c = 2 will factor it.

Brent's algorithm

Brent implements a similar method to Floyd, using two pointers. The difference being that instead of advancing the pointers by one and two places respectively, they are advanced by powers of two. As soon as 2i2^i is greater than λ\lambda and μ\mu, we will find the cycle.

text
function brent(f, x0):
    tortoise = x0
    hare = f(x0)
    l = 1
    while tortoise != hare:
        tortoise = hare
        repeat l times:
            hare = f(hare)
            if tortoise == hare:
                return true
        l *= 2
    return true

Brent's algorithm also runs in linear time, but is generally faster than Floyd's, since it uses less evaluations of the function ff.

Implementation

The straightforward implementation of Brent's algorithm can be sped up by omitting the terms xl−xkx_l - x_k if k<3⋅l2k < \frac{3 \cdot l}{2}. In addition, instead of performing the gcd⁡\gcd computation at every step, we multiply the terms and only actually check gcd⁡\gcd every few steps and backtrack if overshot.

text
long long brent(long long n, long long x0=2, long long c=1) {
    long long x = x0;
    long long g = 1;
    long long q = 1;
    long long xs, y;

    int m = 128;
    int l = 1;
    while (g == 1) {
        y = x;
        for (int i = 1; i < l; i++)
            x = f(x, c, n);
        int k = 0;
        while (k < l && g == 1) {
            xs = x;
            for (int i = 0; i < m && i < l - k; i++) {
                x = f(x, c, n);
                q = mult(q, abs(y - x), n);
            }
            g = gcd(q, n);
            k += m;
        }
        l *= 2;
    }
    if (g == n) {
        do {
            xs = f(xs, c, n);
            g = gcd(abs(xs - y), n);
        } while (g == 1);
    }
    return g;
}

The combination of a trial division for small prime numbers together with Brent's version of Pollard's rho algorithm makes a very powerful factorization algorithm.

Practice Problems