Fermat's Factorization Method (Close Primes)
- •
What it is
- •
A factorization technique (dating to Fermat, centuries before RSA) that's extremely fast whenever a composite has two factors close to each other in size. Since for , starting from and incrementing by 1 each step while checking whether is a perfect square finds (and hence ) in roughly steps — trivially fast if and are close, hopelessly slow if they aren't.
- •
- •
When to apply
- •
RSA key generation that derives and from a shared starting value (or otherwise biases them toward being close together) — a strong tell is any prime-generation routine that starts both primes from the same random seed and nudges them upward by comparatively small increments until each is prime.
- •
- •
Math
- •
where for increasing , testing whether is a perfect square at each step; once found, , .
- •
- •
Worked example
- •
. Start at ; is already a square, so and the factors are and . Runtime grows with the gap between the factors.
- •
- •
Python
- •
from math import isqrt def fermat_factor(n): a = isqrt(n) if a*a < n: a += 1 b2 = a*a - n while isqrt(b2)**2 != b2: a += 1 b2 = a*a - n b = isqrt(b2) return a - b, a + b
- •
- •
SageMath
- •
is_square()andceil(sqrt(n))tidy the syntax, but the loop structure is identical to the Python version — this isn't a case where Sage changes the approach.
- •
- •
Related
- •
Cards
- •
What structural weakness does Fermat's factorization method exploit?
- •
The two prime factors being close in size — the closer they are, the fewer iterations the search needs.
- •
- •
What's the core algebraic identity behind the method?
- •
N = a² - b² = (a-b)(a+b), searching upward from a = ⌈√N⌉ for the first a where a²-N is a perfect square.
- •
- •