-
The modulus chorus plays for us
09/21/2026 at 00:55 • 0 commentsBack on the breadboard, I'd factored 5,283,065,753,709,209 with three ATtiny moduli. It took 25 minutes, about as long as Lehmer's 1932 gear machine, even though the breadboard sieve can run ten times faster. Having only three moduli let through 740,000 survivors, which the Pico has to check. This left the sieve idle over 90% of the time waiting on the Pico.
With 30 moduli the same problem now finishes in under two minutes, about ten times faster than the gear machine, as expected. Only two candidates survive, and both are real solutions. Two of Lehmer's gears accept every value on this problem and do no filtering at all, so those two cards stay dark for the whole run. He couldn't swap in different moduli because they were fixed by the gears he had, but the remaining 28 still filtered enough. My current sieve is also ten times faster than the breadboard version, so at its full rate of 500,000 numbers per second the same run takes 11 seconds.
With the machine now fully working, over several hours I ran published problems from three of Lehmer's sieves. The 1928 bicycle chain machine, the 1932 gear machine, and the 1965 delay line electronic sieve.
1928 and 1932: bicycle chains and gears
In 1928, Lehmer published [LF28] with results from the bicycle chain machine, and [PS33] and [NF33] in 1933 with results from the gear machine. Each result gives how fast the machine ran, where it stopped, and how long that took.
I set my REQ clock, the shared line that steps every card, to each machine's own rate. That is 50 numbers/sec for the bicycle chain machine, and 5,000/sec for the gear machine. The chain machine had 19 chains, so those runs use 19 cards. The gear machine had 30 gears, so those use all 30.
Problem Paper Rate Published notes My sieve Stops 9,999,000,099,990,001 LF28 50/s "about 2 hours" 2 h 14 min 09 s 2 a factor of 3^111 + 1 LF28 50/s "only 4 seconds" 2.96s 1 4,500,383,424,373
as a sum of two squares, run1LF28 50/s "one stop, not
a solution"1 h 05 min 42 s 1 same problem, run2 LF28 50/s "stopped only once" 52 min 37 s 2 2^79 - 1 PS33 5,000/s "12 s" 11.31 s 1 2^93 + 1 NF33 5,000/s "a few seconds" 1.41 s 1 Every solution matched the published one as expected. Run 1 of the sum of two squares has no solution in its range, so it ran to the end. My measured times agree as well. My sieving rate comes out about 0.5% below the REQ clock rate, from the periodic self-test checkpoints and OLED updates.
Interestingly, I found some minor discrepancies from the published results.
The 1928 paper does not note two of the stops
The bicycle chain machine [LF28] stops when a survivor is found, and a person then checks it by hand. The paper says how many times that happened. On two of the four runs, my sieve stopped one more time than was noted in the paper.
- Sum of two squares, run 2. Paper: "stopped only once", at x = 157,044. Mine stopped first at x = 102,151, a = 510,758, N minus a^2 = 4,239,509,689,809, not a square, 18 minutes earlier.
- N = 9,999,000,099,990,001. Paper: "stopped at x = 400,453". Mine first stopped at x = 257,749, a = 1,955,793,401, a^2 minus N = 3,815,128,827,295,156,800, not a square, 48 minutes earlier.
Neither could have been rejected by that machine. Both are quadratic residues of every prime up to 67, its largest chain, and the smallest prime that rejects them is 73. So the machine would have stopped. I'm assuming these were just left out of the final write-up.
Two smaller items
[PS33] gives the wrong period for the gear machine (the number of steps before the initial gear positions repeat) as 2497194316592991015263471297031949336968700272210.
- That number is actually the product of the first 30 primes, with 79 multiplied in twice
- The first 4 gears actually have prime power tooth counts, 64, 27, 25, 49. (The rest were the remaining primes 11 to 113)
- These are all coprime, so the true period is the product of the gear teeth counts 318629350775409486504503679418760117932208844859200. That's about 128 times higher than the reported number.
Not every gear or chain helps on every problem.
- On 2^79 - 1, moduli 64, 27 and 79 accept every candidate, so those three gears played no part in the sieving.
- The same happens on the chain machine. On N = 9,999,000,099,990,001, chains 64 and 25 accept everything, so Lehmer would have pinned every link on both these chains.
- With fixed teeth or fixed chain lengths there was nothing to be done about it. On my sieve the affected cards are visible as dark cards during the run.
- Lehmer talks about this in his 1982 lecture, describing thebenefits of an adjustable sieve design mine recreates: "...we don't have to commit ourselves hardware wise to the set of modulus that we use..."
1965: the delay line sieve
The DLS-127 electronic sieve used surplus Navy delay lines, one per modulus, and stepped 1,000,000 candidates per second, twice my board's 500,000. The ring patterns were generated on a CDC 6400 and punched onto a 25 foot paper tape of 2,877 characters, which was read into the machine through a photoelectric tape reader [DHL82]. It was then left to run, printing surviving numbers on a Clary printer for a separate step where each number could be verified.
The Lehmers published six problems solved on it [LLS70], but no running times anywhere. I've shown the running times on my board instead.
Problem published value at p=127 My sieve's running time I 196,265,095,009 4 h 33 min II 328,878,692,999 7 h 39 min III 71,837,718,283 1 h 40 min IV 8,133,814,327 11 min 21 s V 60,664,576,541 1 h 24 min VI 9,447,241,877 13 min 11 s Many of these are multi-hour runs, running at the full-speed my sieve is capable of - but every one of these runs worked without errors. All checkpoints passed, and the sieve successfully found the same published results.
There was one oddball problem which was interesting to realize.
Problem I produces 50,000 survivors, and the rest produce one
Problem I asks for a pseudosquare, the smallest number above 1 that is 1 modulo 8 and a quadratic residue of every odd prime up to 127. It is unique among the six, producing over 50,000 survivors over its run, while the others all stop once, on the solution.
The reason is simply that every odd perfect square also passes the modulus checks, so they show up as survivors, and have to be checked and discarded.
DLS-127 had no way to test a survivor as it arrived, and it would have been impossible to check 50,000 numbers printed on paper. Instead Lehmer used a second capability of the machine. It could count survivors without printing them, and the number of perfect squares could be calculated from a second, much simpler sieve run. By running both problems alternately and doing a binary search on the range, Lehmer isolated the single survivor that was not a square.
My sieve follows the later designs, where a controlling computer checks survivors as they arrive. The Pico discards the squares as they come out, without ever holding up the sieve so my run was very straightforward.
Why these machines lasted so long
A sieve is fast because rejecting is cheap. It does no arithmetic, so it picks up every improvement in hardware without having to implement complex instruction and memory stages. So electromechanical chains at 50 numbers per second became VLSI at 6.4 billion over 70 years, and why the machines were still winning on some problems into the 1990s.
What ended them was a better algorithm, not faster hardware. A sieve is still brute-forcing its way through every integer in its range. In 2001 Bernstein showed how to take the same moduli and generate the survivors directly via an algorithm that was fast to run on a general purpose computer. This removed any reason to build such hardware from then on.
-
The modulus chorus rehearses
09/15/2026 at 18:21 • 0 commentsHere is a self-test running across all thirty cards on a stripboard backplane. Each LED lights in slot order while the OLED reports the address it is checking.
Last time, I tested the cards one at a time. They now sit in a stripboard backplane with 30 headers, which brings its own failures. A cold joint or a bridge on the backplane, or a card not seated far enough into its header. A card that incorrectly holds the shared VOTE line low rejects candidates that should pass. This causes the run to silently fail, as every valid solution is discarded before verification by the Pico. The machine now checks itself before it starts. I also wanted to know how fast it can run, so I measured two things on VOTE with all 30 cards fitted: how long after a REQ edge a card pulls the line low, and how long the line takes to return high once every card has released it.
The stripboard backplane
I built it on a 3U Eurocard stripboard, with 62 holes along each of 38 copper strips.
![]()
Fitting thirty 8-pin daughter cards, a Pico and an OLED is tight. I tried several layouts in diylc before settling on three rows of ten, with the Pico on the left and the OLED in the corner beside it. The Pico's right-hand column of pins lands on the same strips as the first card slot, so ground, SDA, SCL, VOTE and REQ reach it directly. Vcc is taken off a jumper from the 3V3 pin on the Pico.
An ATtiny412 draws 2.7 mA running at 10 MHz, and each LED about 1 mA, so thirty cards with every LED lit come to roughly 111 mA. The OLED takes an additional 20 mA or so. The Pico's regulator is rated at 800 mA, so the 131 mA total leaves plenty of margin.
![]()
The strips are on the underside, so everything is mirrored once the board is turned over to work on them. I drew the component outlines on the top side first, and poked a wire through each hole to confirm a position before cutting anything.
![]()
To break a strip I spot-face a hole. I place a drill bit at a hole and gently turn it by hand until the ring of copper around it is gone, then verify that the two sides of the break are no longer connected. Stripboard has no solder mask, so solder spreads about one hole's width along the strip from every joint. If you solder first, cutting through it can be difficult. So I made the breaks first, then the jumpers while nothing tall got in the way, and the headers last.
![]()
![]()
![]()
Flashing thirty cards
Each card gets its own I2C address as a compile-time define, so a batch script walks through all thirty, one at a time. It rebuilds the binary for each address and prints which slot the card goes into. Slotting them sequentially along the rows makes it easier to tie an I2C address to a physical position when something goes wrong later.
After the shipping image is flashed, the jig talks to the card over I2C: it reads STATUS back, loads a modulus-7 ring, steps 14 REQ edges by hand, and checks VOTE against the pattern that ring should produce. I couldn't do this in the last build as there was no I2C firmware to talk to yet.
A failure doesn't advance the address counter, so I can reseat the card and retry. Poor seating in the jig socket was the only failure I saw during flashing.
![]()
![]()
Self-checks
With one open-drain VOTE line driven by 30 cards and no error detection, a single mistake can silently make a run worthless. A card stuck holding VOTE low rejects valid candidates, and the run then completes and claims no solutions exist.
I first enhanced the I2C protocol, to make it more robust and to let me inspect each card's internals. I added a CRC-8 checksum, and each command always returns a single-byte response code. So a card can reject a corrupted command and inform the Pico, rather than silently doing something unexpected. I added a STATUS command to return the card's ring position, whether it is armed, its modulus, firmware version and why it was last reset. The reset reason shows whether a card was reset by a brownout part-way through a run.
I then wrote a set of checks that run before the sieve starts.
- Run an I2C scan to collect and verify the addresses of devices that respond, including the OLED.
- Rerun the scan with REQ held high, then low. Any bridge to REQ makes the two address lists different
- Idle VOTE: disarm every card, then run 10 REQ edges. VOTE should stay high throughout
- LED walk: light each card's LED in slot order, one at a time. Watching it move down the rows confirms that a card's I2C address matches where it physically sits
- Arm one card at a time, clock REQ, and compare VOTE against the pattern that card's ring should produce.
When the board first came up, three of thirty slots did not answer the I2C scan. I could identify them quickly, both by the address and by the LED walk, which skipped the problem boards. Simply re-seating the cards fixed all three. On closer inspection the fault was likely some debris that fell into the female headers, not the solder joints themselves. The female headers seem to collect lint.
All the self-checks passed once I reseated the cards, so I have some confidence there are no bridges, shorts or opens on the four shared lines: SDA, SCL, REQ and VOTE.
Faster VOTEs from the tinys
Clock correction first. The tinys run at 3.3 V, and are only rated for 10 MHz at that supply. I was incorrectly testing at 20 MHz in a prior log, when I measured around 5 µs (100 cycles at 20 MHz) to cast a vote. At 10 MHz that same code would have taken 10 µs before it voted.
I moved the VOTE code directly into a hand-written interrupt handler. It reserves a few registers and pre-computes the vote, so the first instruction in the handler drives the VOTE line. The interrupt is cleared and the vote for the next edge is computed before it returns from the handler. What remains is the time for the ATtiny to detect the edge and reach the interrupt vector.
I measured around 950 ns from the REQ rising edge to VOTE low at 10 MHz, against 5 µs in the previous build at 20 MHz. That is a five-fold improvement, while running at half the clock speed.
![]()
Reducing the VOTE release time
In a prior log the VOTE line took about 10 µs to release, using only the Pico's internal 50-60 kOhm pull-up. In this version I enabled the pull-ups across the tinys as well, about 20-50 kOhm per card, 35 kOhm typical. Thirty of those in parallel come to around 1.2 kOhm. Each card also adds a small capacitance to the line, but the drop in resistance should have a much larger impact.Measured on the stripboard: REQ rising edge to VOTE settled high, 1.684 µs. That is one candidate every 1.684 µs, or about 600,000 a second.
![]()
That 1.684 µs includes the 950 ns the tinys take to vote, so the line itself takes around 700 ns to charge. I could keep shaving cycles off the tiny code, but that 700 ns is set by the pull-up resistance and the capacitance of the line and the thirty cards on it. A smaller pull-up would shorten it, at the cost of more current that needs to be sunk by every card that votes to reject.
Getting into the MHz range needs a different arrangement: each card driving its own VOTE line actively, with all thirty collected in a wide AND gate. That is what the later machines did. The 1965 delay-line sieve and the shift-register machine around 1980 both used active drive rather than one shared open-drain line.
Links to the firmware and self-test code is here on GitHub.
Next, some results from sieving runs.
-
Qualify the moduli
09/12/2026 at 00:44 • 0 commentsThe boards are here, and they are smol!
![]()
![]()
Soldering headers across 30 cards is 240 joints, and any one could break the sieve silently. An open joint only costs time. More candidates survive, and the Pico has to check each one. A bridge to ground on VOTE is worse. The card will reject candidates that should pass, and the run ends without a solution.
On a shared bus, any of the thirty could be the culprit. I have to flash each card individually anyway, so I can also test each in isolation before flashing it.
Soldering headers
Soldering a right angle header on a small board like this can be tricky to keep the pcb aligned with the pins. I used a sacrificial female header under the ground side of the pcb, which is component free and flat. I inserted the right angle pins in another female header, which keeps the pcb in the same plane as the pins, and then solder the headers.
![]()
![]()
The test jig
The jig is just a small stripboard with two 8-pin male headers to secure it to a breadboard and a female header for the card under test. A Pico to test for open/shorts and a UPDI Friend to flash the code stay on the breadboard. The cards are never inserted or removed from the breadboard directly, avoiding damage over 30 cards.
![]()
![]()
The test software
I first flash test code that just leaves the four bus lines in high-Z with pullups, and blinks the LED as a visual check it works. The Pico drives each line low in turn and checks the others are still high. This find bridges between lines. It then releases everything and checks all lines are high. The pullups are in the tiny, so any open connection would stay low.
Here's a successful run.
================================================== Stage 2: Running electrical self-test via Pico ================================================== Local directory . is mounted at /remote ================================================== ATtiny412 Flash-Time Self-Test Jig ================================================== [1/4] Check 1: Shorts to GND ... [PASS] [2/4] Check 2: Pin Bridges & VCC Shorts ... [PASS] [3/4] Check 3: Open Circuits ... [PASS] [4/4] Check 4: JP1 & PA7 Isolation (3.0s) ... [PASS] ================================================== RESULT: ALL CHECKS PASSED. Card is verified. Ready for final shipping image. ==================================================Here's one with a failure, indicating a bridge between two pins.
================================================== Stage 2: Running electrical self-test via Pico ================================================== Local directory . is mounted at /remote ================================================== ATtiny412 Flash-Time Self-Test Jig ================================================== [1/4] Check 1: Shorts to GND ... [PASS] [2/4] Check 2: Pin Bridges & VCC Shorts ... [FAIL] -> ERROR: Bridge detected: driving PA6 (H1-2) pulled down PA7 (H1-3) -------------------------------------------------- RESULT: FAILED. Do NOT flash final image. --------------------------------------------------Finally, the real code is flashed over. There's more to say about the actual code, but I'll save that for the next log.
The code for the test jig is here on GitHub.
Here's a video of how using the test jig looks like.
-
A modular modulus
09/08/2026 at 18:54 • 0 commentsAt the end of the last build, my 3 moduli let 740,000 of 5.68 million candidates through, and the Pico spent 23 minutes checking them. The sieve was idle 92% of the time - filter-bound, generating survivors faster than the Pico could check them.
I need more moduli. Twelve would drop checking to a few seconds, and the 1932 gear machine ran 30. So it's time to leave the breadboard and make each modulus a card I can plug into a backplane.
The hardware
My plan is a stripboard bus with female headers, with each modulus an ATtiny412 on a card standing vertically in it. All pins come out to one edge, with a decoupling cap on the card. I want to keep the UPDI programming pin free. SDA and SCL sit on PA1 and PA2. That leaves PA3, PA6 and PA7 for REQ, VOTE and one spare. PA7 has the peripherals I'm least likely to need, so it drives an onboard LED and each card blinks its own vetoes.
The schematic is an ATtiny412, a decoupling cap, an LED with its resistor, and a header. The one addition is a jumper that ties PA7 to a header pin, in case I want that line off the card instead of the LED.
![]()
Routing fits entirely on the top layer. I rounded the traces for the look of a hand-drawn PCB, and rounded one corner so I can check that 30 cards are all seated the same way.
![]()
![]()
I drew the schematic and board in JLCPCB's online editor and picked parts they stock so the boards arrive assembled. Hand-soldering 30 sets of SMD parts is not something I want to do, so the header pins are all I have to solder.
Thirty boards came to $81 with shipping and tariffs, or around $2.70 a modulus. Each board is identical, since the modulus is loaded over I2C at the start of a run.
Gerbers, Altium source and the JLCPCB BOM are in the GitHub repo if you want to order your own.
-
Sieving versus checking
09/06/2026 at 19:14 • 0 comments![]()
Got these three ATtiny412s and a Pico to factor 5,283,065,753,709,209 - the number D.H. Lehmer's gear machine factored in 1932.
The sieve scanned 5.6 million candidates in 113 seconds and rejected 87% of them. The Pico spent 23 minutes testing the 740,000 that survived. The sieve is idle for 92% of the run, waiting for the Pico to check survivors.
So a sieve which scans ten times faster than Lehmer's 1932 gear machine, takes about as long to factor the same number. The difference is the number of moduli. The three moduli let through around one in eight candidates. Lehmer's thirty let through so few that a human could hand-check the survivors without adding much more time to the process.
Where the candidates come from
The first build log showed how to sieve y^2 - 2x^2 = 4001. Factoring is the same kind of problem - find whole numbers that satisfy a quadratic equation.
Take any odd number N = p*q. Both factors are odd, so their sum and difference are even, and a = (p+q)/2 and b = (p-q)/2 are whole numbers. Then N = a^2 - b^2. So find a and b, and the factors are a+b and a-b. So factoring can be expressed as a quadratic equation to solve in whole numbers.
To sieve it, a starts just above sqrt(N) - about 72 million for our 16-digit number - and climbs. Our two factors turn out to be very far apart, 59,957 and 88 billion, so a reaches a solution after 44 billion. At the gear machine's 5,000 candidates a second that would be 102 days of continuous running.
Lehmer did an additional reduction in number theory first. He showed the number must be of the form a^2 + 7b^2, and that a second solution c^2 + 7d^2 gives a factor directly as gcd(N, ad + bc). He also showed b must be a multiple of 4, so we actually solve for a^2 + 7*(4*k)^2 = N
That leaves about 6 million candidates to check with the sieving machine.
Here's what our console log from the RP2040 shows - we stop at the second solution for our equation after 1,471 seconds and scanning 5,676,028 numbers.
... >>> FOUND REPRESENTATION: M = 66855539^2 + 7 * 10779628^2 (k = 2694907, 706.32s) <<< ... >>> FOUND REPRESENTATION: M = 40923451^2 + 7 * 22704112^2 (k = 5676028, 1471.69s) <<< ============================================================ FACTORIZATION COMPLETE in 1471.69s! Factors of 5283065753709209: Factor 1: 59957 Factor 2: 88114244437 Verification: 59957 * 88114244437 == 5283065753709209 (True) ============================================================Every sieve has something slower behind it
A sieve only rejects candidates. Whatever survives has to be checked by something else, and that something else is always slower (or the sieve wouldn't be useful.)
In 1928 the Lehmers built a sieve from 19 bicycle chains on a common shaft, one chain per modulus, with a twist of chickenwire at each accepted link tripping a microswitch, and a revolution counter for the current number. The switches were wired in series, so a candidate nobody rejected completed the circuit and stopped the motor. Then a person checked if the candidate was a solution.
A 1932 machine built with gears replaced chains with steel gears and the switches with a beam of light through aligned holes. A photoelectric cell would detect when all holes lined up and stop the motor.
![Some of the moduli in the gear sieve Some of the moduli in the gear sieve]()
Some moduli in the 1932 Lehmer gear sieve: Photographer: Marcin Wichary (CC BY 2.0) ![Rejected positions plugged up with toothpicks Rejected positions plugged up with toothpicks]()
Rejected positions plugged up with toothpicks: Photographer: Marcin Wichary (CC BY 2.0) Every number sieve ever built has the same two stages: a fast rejecter and a slower checker. New technology simply changed what each stage was made of, allowing larger and larger problems to be solved: from 60 candidates a second in 1928 to 6.4 billion in 1995, through bicycle chains, steel gears, surplus Navy delay lines and finally custom VLSI.
Machine type year moduli candidates/sec who checks survivors bicycle chains 1928 19 60 human 16mm film ~1930 18 60 human steel gears 1932 30 5,000 human delay lines 1965 36 1,000,000 printer, CDC 6400 shift registers (Winnipeg) ~1980 32 132,000,000 host minicomputer ROM + counter (Berkeley) 1982 -- 16,600,000 host computer VLSI (MSSU) 1995 30 6,400,000,000 host computer By 1982 all sieving machines were built as a special purpose device built to reject as fast as possible, and a general-purpose computer that loaded the patterns, drove the clock, and tested the survivors. My build is that architecture as well.
What ended the sieve machines was better algorithms, not faster hardware. Sieving stopped being the fastest way to factor around 1970, but the machines were used through the 1990s on other number-theory searches. A sieve is fast because rejecting is cheap, but it still steps through every integer in the range. In 2001 D. J. Bernstein demonstrated a method that takes the same moduli and generates the survivors directly, ending the need for specialized number sieving machines.
Three chips and a Pico
My design is based on a sieving machine D.H. Lehmer described during this 1982 lecture. It's a great watch if you're into oddball contraptions to solve deep number theory problems.
In the 1982 version, each gear becomes a bit pattern in ROM with a counter indexing it. I'll call this repeating pattern a ring. The beam of light becomes a shared line driven by the ROM values, and the revolution counter is within a general purpose computer that sets up the moduli, drives the device and checks survivors for solutions.
I use an ATtiny412 for each ROM/counter per modulus, and an RP2040 as that computer.
![]()
Each ATtiny is initialized over I2C with its ring - a circular bit-array of accept/reject bits (the first build log's row of yes/no values). The ring is saved in RAM, so it can be initialized to any modulus. The 412 has 2048 bits (256 bytes) of RAM available, but I limited the moduli to be 128 or less for now. This also allows loading arbitrary moduli, unlike sieve machines that have a hard-coded set of moduli in their design.
Lehmer called these 'adjustable sieves" - useful for problems where you had to choose the moduli carefully to get useful sieving. In my case, I can also use it to replicate the various historical machines to get a realistic sense for how they worked, which should be fun.
All tinys share one open-drain line, VOTE. They release it to accept, or pull it low to reject. A survivor is found if this line stays high. An open-drain line keeps the wiring simple, though the scanning speed is limited by the RC constant on it. Running in the high MHz would likely need a wide AND gate with the tinys actively driving the line.
The tinys are clocked with a common REQ line so they can drive the VOTE line in lockstep as they increment their ring counters. They have to start together as well. A ring one position off votes against the wrong number, and silently corrupts all results.
The Pico first holds REQ low and initializes the rings over I2C, sending each ATtiny its modulus and ROM bit pattern, and resetting its counter to zero.
Once initialized, on the rising edge of REQ every ATtiny drives VOTE from its current bit and advances its ring counter, wrapping at its modulus. The candidate number never reaches the ATtinys - they only ever advance their ring counter and read a bit.
The Pico samples VOTE after the falling edge. If VOTE is still high, no chip rejected, and the Pico computes M - 7(4k)^2 and tests whether it is a perfect square.
The Pico drives REQ, monitors VOTE and updates a 64-bit counter all in PIO. It pushes candidates over a FIFO, which the main CPU then checks. This was my first time really getting into PIO and I was surprised at how much functionality you can squeeze out of it.
The firmware and pico code including the setup to factorize our 16-digit number is all available in GitHub here.
Things I also measured
First, I pre-calculated survivors for the first 10,000 candidates and compared it with what the sieve produces.
--- Mode A: Lint & Verification (first 10000 candidates) --- Expecting 1305 survivors (13.05% pass rate)... PASS: 100% agreement over 10000 candidates (199.9 ms, 50.04 kHz).The three ATtinys agreed with the pre-calculated list on each of the first 10,000 candidates, so the VOTE logic seems to be working.
Moduli 5, 11 and 23 accept 3/5, 5/11 and 11/23 of candidates, predicting 13.043% survival. Over the full run it measured 13.044% and that checks out too.
I also took some scope traces on the REQ (blue trace) and VOTE (yellow trace)
![]()
When REQ rises, VOTE is pulled low after about 5us. That 5 us is the ATtiny (around 100 cycles at 20Mhz) to handle the interrupt, read one bit, advance the counter, drive the pin. Currently the tinys set a flag on a rising interrupt on that pin, and a main loop waks up to drive the VOTE line. If needed, I could roll this into the interrupt handler and do it quicker.
The VOTE open-drain line releasing on a candidate shows an RC curve than an edge, taking around 10.1us to reach the supply.
![]()
The code currently just uses the internal pullup on the Pico - around 50-60kOhm. The RC constant is around 2us, so we might have around 35pF on the line between the breadboard and the probe.
A candidate therefore takes 5 us of attiny compute and 10 us of RC, so I clock REQ every 20 us, 50KHz.
A smaller resistor pulling up the line should bring the RC constant down, and we could optimize the ATtiny code as well. So, I think there's some headroom to increase the scanning speed if needed.
Checking a survivor however is an order of magnitude more expensive - that takes around 1.85 ms on the Pico, or about 92 REQ periods.
![]()
This is what it looks like on the scope. A short burst of REQ pulses picks up a new survivor, then a long flat stretch with VOTE high and no clock at all. The sieve is waiting here for the Pico to finish square root calculations.
A sieve machine in this state is said to be "filter bound" - the survivor rate overwhelms whatever is checking survivors, so the machine runs far below the rate the sieving device can sustain.
The fix is more moduli.Each added coprime modulus rejects about half of what is left, so for instance twelve moduli would leave around 1,100 survivors instead of 740,000. Checking time with 12 moduli should drop from 23 minutes to 2 seconds, and the run would be dominated by the roughly 2 minutes of scanning at 50KHz.
-
The sound of sieving
09/01/2026 at 17:41 • 0 commentsHow would you solve an equation like
This isn't too hard of course, we can write
to get all possible x, y pairs. But what if we constrain x and y to be positive whole numbers?
Equations like this are Diophantine Equations, and are known to be hard to solve in the general case - e.g. with arbitrary powers and terms. If it has only squared terms like this (quadratic Diophantine equations) they are still known to be NP-complete, so we don't have any good way to solve them quickly either.
Let's try to brute-force our example anyway.
What we're looking for, are numbers of the type:
which are themselves square numbers, since y needs to be the square root.
Let's check for x = 1 - we get 2*1^2 + 4001 = 4003 - it's not a square number
Let's try a few more
x 0 1 2 3 4 5 6 7 8 9 2x^2 + 4001 4001 4003 4009 4019 4033 4051 4073 4099 4129 4163 You might instinctively notice that some of these numbers - e.g. - 4033 don't look like it could be a square.
In fact, any perfect square ends in 0, 1, 4, 5, 6 or 9. The last digit (in base 10) is just arithmetic modulo 10, and so we can discard about half our numbers without going through the bother of actually calculating the square root.
We can do the same trick with a different base - let's take everything modulo 3, and see where that gets us
x mod 3 0 1 2 x^2 mod 3 0 1 1 2x^2 + 4001 mod 3 2 1 1 could be square? no yes yes The second row tells us only 0 and 1 can be perfect squares in mod 3 arithmetic.
The third row tells us that 2x^2 + 4001 = 2 mod 3 when x is 0 mod 3, and the second row tells us that 2 can never be a perfect square mod 3.
So this means any x that's 0 mod 3 can't be a solution either.
So we can skip about a third of our brute-force check already.
Let's do this trick for a couple more moduli
x mod 5 0 1 2 3 4 x^2 mod 5 0 1 4 4 1 2x^2 + 4001 mod 5 1 3 4 4 3 could be square? yes no yes yes no mod 5 lets us avoid checking about 40% of our numbers
x mod 7 0 1 2 3 4 5 6 x^2 mod 7 0 1 4 2 2 4 1 2x^2 + 4001 mod 7 4 6 5 1 1 5 6 could be square? yes no no yes yes no no mod 7 lets us skip checking around 60% of our numbers.
x mod 11 0 1 2 3 4 5 6 7 8 9 10 x^2 mod 11 0 1 4 9 5 3 3 5 9 4 1 2x^2 + 4001 mod 11 8 10 5 4 7 3 3 7 4 5 10 could be square? n n y y n y y n y y n and mod 11 lets us skip about 50% of our numbers.
We could of course keep stacking these tests. If we use prime moduli, each new modulus removes about half the candidates, so this gets very effective very fast. If we use k moduli, only about 1/2k candidates survive the test. (The initial few primes usually remove less than half, so in practice sieves don't bother with moduli smaller than 9.)
The sieving mathematicians
Imagine you have four people in a room - one per modulus. Each of them has just the last row of yes/no values for their table. So we have one person holding the mod 3 row, another holding the mod 5 row, and so on.
A fifth person - a scorekeeper - holds a counter set at 0, and then shouts "vote".
Everyone looks at their first cell - if it says "no" - they shout "no". If it says "yes", they keep silent. Then, they move their finger to the next cell and wait for the scorekeeper. If they get to the end of their row, they just start over.
Most of the time, one or more people would have shouted no, and the scorekeeper just clicks their counter and shouts "vote" again.
Every once in a while, nobody in the room would have veto'ed that number. The scorekeeper looks at their counter, and checks if it could be a solution. If not, they keep moving on.
Let's see how this plays out in our example for the first 10 steps. Notice how the mod 3 and mod 5 rows just repeat every 3 times and 5 times respectively. Each row is just a pattern that repeats with a period equal to its modulus.
scorekeeper 0 1 2 3 4 5 6 7 8 9 10 the mod 3 person N -- -- N -- -- N -- -- N -- the mod 5 person -- N -- -- N -- N -- -- N -- the mod 7 person -- N N -- -- N N -- N N -- the mod 11 person N N -- -- N -- -- N -- -- N At least one person vetos every number through 10, and the scorekeeper just keeps clicking their counter. In fact, the first silence the scorekeeper hears is at 17, so they avoided checking all the previous numbers, and see if 17 could be a solution. 2*17*17 + 4001 = 4579 which isn't a perfect square, so they keep going. The next silence is at 25, then 28, and 35 - none of which are solutions. The next silence is at 38. 2 * 38 * 38 + 4001 = 6889 which is 83*83, so we have our first solution after checking only about 13% of all the numbers.
At four moduli, we were expecting to check only about 1/2^4 ~ 6% - but the initial small primes - 3 and 5 - only remove about a third, so we might have done better with slightly larger moduli.
The sieving ATtinys
Here is that room of people, built from three ATtiny412s.
![]()
Each ATtiny is programmed to hold the sequence for mod 3, mod 5 and mod 7. They listen on a shared line connected to a push-button switch. Anytime it goes low, they check the array and briefly pulse a different "veto" pin low.By default, the veto pins are pulled high across the tinys, and in high-Z mode (as inputs.) Pulsing briefly turns the pin to an output driving low, pulling it to ground. I can also connect all the veto pins together to get one line that rejects if any of the devices rejects.
I bread-boarded it and hooked up a buzzer to hear the rejected votes, and the repeating sequences from each ATtiny. Jumpers isolate each ATtiny for debugging. Hooking the buzzer to the shared line also shows how adding more moduli rejects more numbers audibly.
![]()
And here's a video so you can hear the rejections.
kbsriram


























