← LibraryTrial Division and Lehman's MethodEngineering · MathematicsLesson 355/385← PrevNext →
ArticlePublished 7 Aug 20262 min readBy Kevin Jogintrial divisionFermat methodLehman methodsmall factors

Classical Primality and Factoring

Trial Division and Lehman's Method

Trial division as the first factoring step, its cost, and Lehman's improvement on Fermat's method.

Engineering / MathematicsClassical Primality and Factoring2 min readKV-MATH-0652

Trial division is the first step of every factoring attempt and it handles the great majority of numbers encountered in practice. Knowing when to stop is what matters.

Trial division

Divide by successive small primes up to a chosen bound. Any factor below the bound is found; nothing above it is.

Trial division bounds
BoundCostFinds
A few hundredNegligibleMost factors of random numbers
A millionFastClears the vast majority of composites
BeyondDiminishing returnsBetter handled by ECM

Implementation

Fermat's method

Fermat's method searches for a representation of the number as a difference of two squares, which immediately gives a factorisation.

n = x^2 - y^2 = (x-y)(x+y)Search x upward from the ceiling of the square root.

Lehman's method

Lehman generalises Fermat by searching for a difference of squares after multiplying by a small integer, which handles unbalanced factors much better.

Search over small k for x^2 - y^2 = 4 k nRecovers factors in a bounded range of ratios.
Elementary factoring methods compared
MethodCostBest for
Trial divisionProportional to the smaller factorSmall factors
FermatProportional to the gap between the factorsNearly equal factors
LehmanCube root of the numberGuaranteed bound; small numbers
Pollard rhoFourth root of the numberModerate factors

Practical sequencing

Factoring strategy

  1. Trial divideTo a modest bound.
  2. Test the cofactor for primalityUsing Baillie-PSW.
  3. Check for perfect powersSee perfect powers.
  4. Apply rho or ECMFor moderate factors.
  5. Apply a sieveFor the hard remaining cases.

Source. Henri Cohen, A Course in Computational Algebraic Number Theory, Springer GTM 138 — 8.5.1-8.5.2. Structural reference unverified: the source file was not available during authoring; chapter and section numbers are taken from the published edition and have not been checked against a physical copy.

Continue learning

N+1 Tests and the Lucas-Lehmer TestArticle · MathematicsNEXT LESSON →The Pollard Rho Factoring MethodArticle · MathematicsThe Pocklington-Lehmer N-1 Primality TestArticle · MathematicsThe Pollard p-1 MethodArticle · Mathematics