Factoring With Bicycle Chains
April 4, 2014
As penance for teasing you on April Fool’s Day, I have another exercise on factoring. Today we will simulate a machine invented by Derrick H Lehmer (the son of the famous father-son-daughter-in-law trio of mathematicians named Lehmer) that uses bicycle chains to factor integers. Unlike the previous exercise, this factoring method is real; in fact, a variant of this method was the best available method to factor integers from the mid-1930s to the mid-1960s, and Lehmer’s machine found many valuable factorizations for the Cunningham Project. We’ll discuss a simplified version of the machine today, as described by Uli Meyer, and the full version of the machine in a future exercise. I am unable to find a copyright-free picture of Lehmer’s machine, but if you’re interested you could visit the Computer History Museum, or see Lehmer himself describe the machine.
The machine is based on Fermat’s method of factoring by a difference of squares: if n = x2 − y2 then the factors of n are (x − y) and (x + y). Fermat’s method starts with y = ⌈ √n ⌉, computes y2 − n, and stops when the result is a square.
Lehmer’s machine identifies likely squares by looking at quadratic residues. An integer a is a quadratic residue modulo n if there exists some x such that x2 ≡ a (mod n). For a number y2 − n to be a square in Fermat’s algorithm, it must be a quadratic residue to many small bases. Lehmer’s machine represents quadratic residues as “open” points on a bicycle chain, then spins many bicycle chains of different lengths along a common axis and stops when all are quadratic residues; in many but not all cases, such a number will will indicate a factor of n.
Uli Meyer gives a better description, shows a useful diagram, and provides photos of his Lego sieve machine.
Your task is to write a program that simulates Lehmer’s machine to factor integers. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
Typo in the second paragraph: I believe you mean n = x² − y²?
@Lucas: Fixed. Thank you.
Here’s my work so far… It doesn’t seem to work, but I can’t figure out what’s wrong.
Figured out what I did wrong. Using “all()” at line 38 doesn’t advance every chain; it just advances them until it reaches a chain that reads “False” and then stops, completely ignoring the rest of the chains. Here’s the fixed code:
And here it is as a single function:
When executed with CPython, this finishes in about 37 seconds on my computer while PyPy only needs 4.6 seconds.