TExcelTAD
Home › Number Theory & Cryptography › Factoring Algorithms

Factoring Algorithms

Multiplying two 1024-bit primes takes microseconds. Recovering them from the product is believed to be infeasible for classical computers. This lesson shows the ideas between those extremes: trial division, Fermat's method, Pollard's rho and p−1p - 1, and the sieves used in record factorizations.

Trial division

Divide by 2,3,5,…2, 3, 5, \ldots up to n\sqrt{n}. It finds small factors quickly, so every factoring program starts with it, but a number with two 30-digit prime factors needs about 103010^{30} divisions.

Fermat's method: factors close together

If n=abn = ab with a,ba, b odd and close, then n=x2−y2=(x−y)(x+y)n = x^2 - y^2 = (x - y)(x + y) with x=(a+b)/2x = (a + b)/2 small above n\sqrt{n}. Try x=⌈n⌉,⌈n⌉+1,…x = \lceil \sqrt{n} \rceil, \lceil \sqrt{n} \rceil + 1, \ldots until x2−nx^2 - n is a perfect square. This is why RSA primes must not be too close to each other.

python · try it yourself
from math import isqrt

def fermat_factor(n):
    x = isqrt(n)
    if x * x < n:
        x += 1
    steps = 0
    while True:
        y2 = x * x - n
        y = isqrt(y2)
        if y * y == y2:
            return x - y, x + y, steps
        x += 1; steps += 1

p, q = 1_000_000_007, 1_000_000_123     # close primes
print(fermat_factor(p * q))
(1000000007, 1000000123, 0)

The very first xx works (0 extra steps): when the primes share their top half of digits, Fermat's method is instant, however large they are.

Pollard's rho

Iterate x↦x2+c mod nx \mapsto x^2 + c \bmod n. Modulo an unknown prime factor pp, the sequence must repeat after about p\sqrt{p} steps (the birthday bound). Floyd's cycle detection compares xix_i and x2ix_{2i}; when they agree modulo pp but not modulo nn, gcd⁡(xi−x2i,n)\gcd(x_i - x_{2i}, n) reveals pp. The cost is about p=n1/4\sqrt{p} = n^{1/4} steps.

python · try it yourself
from math import gcd

def pollard_rho(n, c=1):
    f = lambda x: (x * x + c) % n
    x = y = 2
    d, steps = 1, 0
    while d == 1:
        x, y = f(x), f(f(y))
        d = gcd(abs(x - y), n)
        steps += 1
    return (d, steps) if d != n else pollard_rho(n, c + 1)

for n in (8051, 10403, 600851475143, 2**64 + 1):
    d, steps = pollard_rho(n)
    print(n, "=", d, "*", n // d, f"({steps} steps)")
8051 = 97 * 83 (3 steps)
10403 = 101 * 103 (9 steps)
600851475143 = 71 * 8462696833 (11 steps)
18446744073709551617 = 274177 * 67280421310721 (808 steps)

Pollard's p−1p - 1: smooth factors

If p−1p - 1 has only small prime factors (is "smooth"), then p−1p - 1 divides M=lcm⁡(1,2,…,B)M = \operatorname{lcm}(1, 2, \ldots, B) for a modest BB, and by Fermat's little theorem aM≡1(modp)a^M \equiv 1 \pmod{p}. So gcd⁡(aM−1,n)\gcd(a^M - 1, n) is divisible by pp.

python · try it yourself
from math import gcd

def pollard_pm1(n, B):
    a = 2
    for k in range(2, B + 1):
        a = pow(a, k, n)            # after the loop a = 2^(B!) mod n
    return gcd(a - 1, n)

p, q = 1_000_000_009, 1_000_000_021   # p - 1 is 300-smooth, q - 1 is not
from sympy import factorint
print(factorint(p - 1), factorint(q - 1))
print(pollard_pm1(p * q, 300))
{2: 3, 3: 2, 7: 1, 109: 2, 167: 1} {2: 2, 3: 1, 5: 1, 19: 1, 739: 1, 1187: 1}
1000000009

This is why old standards asked for "strong primes" with a large factor in p−1p - 1. With random 1024-bit primes the chance of a smooth p−1p - 1 is negligible, so modern standards no longer insist.

The big guns

  • The quadratic sieve and the general number field sieve (GNFS) collect many relations x2≡y2(modn)x^2 \equiv y^2 \pmod{n} and combine them with linear algebra over GF(2)GF(2). Then gcd⁡(x−y,n)\gcd(x - y, n) is a factor with probability at least 1/2.
  • GNFS runs in time about exp⁡(1.92(ln⁡n)1/3(ln⁡ln⁡n)2/3)\exp\left(1.92 (\ln n)^{1/3} (\ln \ln n)^{2/3}\right): sub-exponential, but still astronomical for 2048-bit nn. The record is RSA-250 (829 bits), factored in 2020 with about 2700 CPU-core-years.
python · try it yourself
import math

def gnfs_cost(bits):
    ln_n = bits * math.log(2)
    return 1.923 * ln_n ** (1 / 3) * math.log(ln_n) ** (2 / 3) / math.log(2)   # log2 of the cost

for bits in (512, 829, 1024, 2048, 3072):
    print(f"{bits:5}-bit modulus: about 2^{gnfs_cost(bits):.0f} operations (heuristic)")
  512-bit modulus: about 2^64 operations (heuristic)
  829-bit modulus: about 2^79 operations (heuristic)
 1024-bit modulus: about 2^87 operations (heuristic)
 2048-bit modulus: about 2^117 operations (heuristic)
 3072-bit modulus: about 2^139 operations (heuristic)

The formula drops lower-order terms, so treat the numbers as rough. NIST's more careful estimates put 2048-bit RSA at about 112-bit security and 3072-bit RSA at about 128-bit security.

In software

  • Tools like msieve, CADO-NFS and YAFU implement these algorithms; SymPy's factorint uses trial division, Pollard rho and p−1p - 1.
  • Real key breaks rarely come from better factoring. They come from bad key generation: shared primes found by gcd, primes too close (Fermat), or weak random generators (Secure Random Numbers).

Exercises

Exercise 1: Fermat by hand

Factor n=5959n = 5959 with Fermat's method.

Answer

5959=59⋅1015959 = 59 \cdot 101.

Solution

⌈5959⌉=78\lceil \sqrt{5959} \rceil = 78, 782−5959=12578^2 - 5959 = 125 (not a square); 792−5959=28279^2 - 5959 = 282 (no); 802−5959=441=21280^2 - 5959 = 441 = 21^2. So 5959=(80−21)(80+21)=59⋅1015959 = (80 - 21)(80 + 21) = 59 \cdot 101.

Exercise 2: Which method?

For each, name the method that factors it fastest: (a) n=p⋅qn = p \cdot q with ∣p−q∣<1000\lvert p - q \rvert < 1000 and 300-digit pp; (b) nn with a 12-digit prime factor and a 100-digit cofactor; (c) a product of two random 1024-bit primes.

Answer

(a) Fermat, (b) Pollard rho (or ECM), (c) nothing practical (GNFS would take far too long).

Solution

(a) Fermat succeeds at the first xx. (b) Rho costs about 1012=106\sqrt{10^{12}} = 10^6 steps, independent of the cofactor. (c) This is the RSA case; GNFS needs about 21172^{117} operations for 2048-bit nn.

Exercise 3: Rho in action (code)

Factor n=1 000 000 016 000 000 063n = 1\,000\,000\,016\,000\,000\,063 with pollard_rho and verify the factors.

Answer

n=1 000 000 007⋅1 000 000 009n = 1\,000\,000\,007 \cdot 1\,000\,000\,009.

Solution
python · try it yourself
from math import gcd
def pollard_rho(n, c=1):
    x = y = 2; d = 1
    while d == 1:
        x = (x * x + c) % n; y = (y * y + c) % n; y = (y * y + c) % n
        d = gcd(abs(x - y), n)
    return d if d != n else pollard_rho(n, c + 1)
n = 1_000_000_016_000_000_063
d = pollard_rho(n)
print(sorted([d, n // d]), d * (n // d) == n)
[1000000007, 1000000009] True

Test yourself

Fermat's factoring method is fast when…

  1. nn is even
  2. the two factors are close to each other
  3. p−1p - 1 is smooth
  4. nn is prime

Pollard's rho finds a prime factor pp in about…

  1. pp steps
  2. p\sqrt{p} steps
  3. log⁡p\log p steps
  4. p2p^2 steps

Which algorithm holds the records for factoring RSA moduli?

  1. trial division
  2. Pollard p−1p - 1
  3. the general number field sieve
  4. Fermat's method