---
title: 'Divstep: Division-Free Algorithm for Reversible Modular Inversion'
url: https://www.emergentmind.com/topics/divsteps
type: topic
---

# Divstep: Division-Free Algorithm for Reversible Modular Inversion

Divsteps is a division-free variant of the extended Euclidean algorithm that computes modular inverses through parity tests, additions or subtractions, division by two, and occasional exchanges of remainder-like values. In reversible computation, divsteps provides the basis for a prime-field modular-inversion architecture discovered through evaluator-guided large-language-model search. The architecture uses arithmetic-state decoding, bounded branch history, measurement-based uncomputation, packed registers, freeze-and-reverse termination handling, and reverse-walk modular halving. For the 256-bit secp256k1 prime, it yields a complete reversible elliptic-curve point adder using $4.0\times10^6$ Toffolis and 935 qubits, while accepting a bounded failure probability [2610.22367].

## 1. Classical algorithm and modular inversion

Given an odd modulus $p$ and a nonzero integer $w<p$, divsteps computes

$$
w^{-1}\pmod p,
\qquad
ww^{-1}\equiv 1\pmod p.
$$

The algorithm is a division-free form of the extended Euclidean algorithm. The ordinary extended Euclidean algorithm maintains integers and coefficients that eventually satisfy

$$
\alpha p+\beta w=1.
$$

Reduction modulo $p$ then gives $\beta w\equiv1\pmod p$, so $\beta$ is a modular inverse of $w$.

Divsteps replaces multi-bit quotient calculations and repeated magnitude comparisons with elementary operations. An odd remainder-like value $f$ is retained while another value $g$ is reduced. If $g$ is even, it is halved. If $g$ is odd, $f$ is added to or subtracted from $g$ before halving, making the result even. A signed counter $z$, also called the half-delta, determines when the roles of $f$ and $g$ are exchanged without explicitly comparing their magnitudes.

The classical divstep state is

$$
(z,f,g,f_v,g_v),
$$

initialized as

$$
(z,f,g,f_v,g_v)=(0,p,w,0,1).
$$

The auxiliary values $f_v$ and $g_v$ track the contribution of $w$ in a scale-dependent form. After $t$ active steps,

$$
f_vw\equiv 2^t f\pmod p,
\qquad
g_vw\equiv 2^t g\pmod p.
$$

The three update cases are

$$
(z',f',g',f_v',g_v')=
\begin{cases}
(-z,\;g,\;(g-f)/2,\;2g_v,\;g_v-f_v),
&z\ge0,\;g\text{ odd},\\[1mm]
(z+1,\;f,\;(g+f)/2,\;2f_v,\;g_v+f_v),
&z<0,\;g\text{ odd},\\[1mm]
(z+1,\;f,\;g/2,\;2f_v,\;g_v),
&g\text{ even}.
\end{cases}
$$

These cases can be represented by two decision bits: $s$, indicating whether the step swaps the roles of $f$ and $g$, and $b$, indicating whether the incoming $g$ is odd. Their values are respectively $(1,1)$, $(0,1)$, and $(0,0)$ for the three cases.

The walk terminates when $g=0$. Assuming $\gcd(p,w)=1$, the resulting $f$ is either $1$ or $-1$. Divsteps preserves the determinant invariant

$$
fg_v-gf_v=p.
$$

At termination this gives $g_v=fp$. Together with the scaling invariant, it follows that

$$
w^{-1}\equiv ff_v\,2^{-t}\pmod p.
$$

Thus divsteps computes the inverse up to a power-of-two scale. For the benchmark modulus, safeGCD analysis guarantees termination within 590 active divsteps for every $0<w<p$.

## 2. Elliptic-curve application and reversible-computation obstacles

The benchmark uses the 256-bit secp256k1 prime

$$
p=2^{256}-2^{32}-977.
$$

The modular inversion occurs in affine elliptic-curve point addition. For a point $P=(P_x,P_y)$ and a classically supplied point $Q=(Q_x,Q_y)$, the slope is

$$
\lambda\equiv(Q_y-P_y)(Q_x-P_x)^{-1}\pmod p,
$$

followed by

$$
R_x=\lambda^2-P_x-Q_x,
\qquad
R_y=\lambda(P_x-R_x)-P_y.
$$

The denominator inversion dominates the point-adder cost.

A classical divstep overwrites its state, whereas a reversible circuit must preserve enough information to reconstruct every overwritten value. A direct reversible implementation would need to retain branch decisions, overwritten arithmetic values, termination information, variable-width and sign information, temporary carries, and comparison results. Four independent 256-bit registers for $f$, $g$, $f_v$, and $g_v$ would already require approximately 1,024 qubits before counters, ancillas, and history.

Reversible implementation introduces several further complications. Branch predicates must be computed, used, and erased while all three divstep cases remain represented coherently. Swaps cannot be treated as ordinary classical variable exchanges whose identities are forgotten. Signed values require two’s-complement handling, sign extension, arithmetic right shifts, and width management. Input-dependent stopping times require either a worst-case schedule or a mechanism that freezes terminated walks. Finally, the scale factor $2^{-t}$ depends on the input-dependent number of active steps.

The architecture addresses these issues without changing the divstep recurrence itself. Its modifications concern representation, control synthesis, history management, uncomputation, stopping-time handling, bounded-resource scheduling, and integration with point-addition arithmetic.

## 3. State-based branch recovery and excursion decoding

The central reversible principle is that the current arithmetic state contains information about many earlier branch decisions. Throughout the recurrence,

$$
f_v\text{ is even},
\qquad
g_v\text{ is odd}.
$$

After a swap,

$$
f_v'=2g_v,
$$

so $f_v'$ has exactly one trailing zero. After a nonswap,

$$
f_v'=2f_v,
$$

and because $f_v$ is already even, $f_v'$ is divisible by four. Consequently,

$$
s=1
\iff
f_v'\equiv2\pmod4
\iff
v_2(f_v')=1.
$$

Every swap therefore becomes recoverable from the updated coefficient register, with no stored swap history.

Parity decisions can also be recovered locally in many cases. For a nonswap with $z'\ge1$, the incoming $g$ must have been even, because an odd $g$ would have triggered a swap. If a nonswap first reaches $g'=0$, the incoming $g$ must have been odd, since halving a nonzero even integer cannot produce zero. These tests recover roughly two thirds of the step decisions. The remaining ambiguous decisions are nonterminating nonswaps entered with $z<0$.

An ambiguous excursion begins with a swap followed by a sequence of ambiguous nonswaps. If

$$
f_v'=2^jq,
\qquad q\text{ odd},
$$

then the associated coefficient update has the form

$$
g_v'=g_v+b2^{j-1}q.
$$

Multiplication by $q^{-1}$ modulo $2^j$ gives

$$
g_v'q^{-1}\bmod 2^j
=
(g_vq^{-1}\bmod 2^j)+b2^{j-1}.
$$

The relevant invariant is

$$
0\le g_vq^{-1}\bmod 2^j<2^{j-1}.
$$

Therefore the top bit of the residue identifies the current branch bit:

$$
b=
\operatorname{bit}_{j-1}
\left(g_v'q^{-1}\bmod 2^j\right).
$$

Using the determinant invariant, an equivalent decoder is

$$
b=
\operatorname{bit}_{j-1}
\left(p(f'q)^{-1}\bmod 2^j\right).
$$

The decoder depends only on the updated state and low-order bits of $f'$ and $q$. The underlying window invariant states that if $z\ge0$, then $2^{z+1}$ divides $f_v$; if $z<0$ and $f_v=2^jq$ with $q$ odd, then there exists $c$ satisfying

$$
0\le c<2^j,
\qquad
g_v\equiv qc\pmod{2^{j-z}}.
$$

This prevents earlier decisions from contaminating the bit used to decode the current one. Immediately after the initiating swap, the window contains a leading 1, while subsequent ambiguous decisions contribute higher binary digits.

For small depths, the modular decoder is compiled into Boolean truth tables. The numbers of product terms at depths 2, 3, 4, and 5 are respectively 3, 3, 11, and 26; at depths 6, 7, and 8 they grow to 79, 268, and 1,092. This growth motivates a tunable boundary between decoding and explicit history storage.

## 4. Architecture, history, and uncomputation

The discovered architecture combines state-based branch recovery, a bounded history stack, measurement-based uncomputation, step-dependent register packing, freeze-and-reverse stopping-time handling, reverse-walk scale removal, and prime-specific modular arithmetic.

Let $j_{\mathrm{store}}$ be the storage threshold. Decisions with $j<j_{\mathrm{store}}$ are decoded from the arithmetic state; decisions with $j\ge j_{\mathrm{store}}$ are stored as history bits. The principal configuration uses

$$
j_{\mathrm{store}}=5.
$$

In sampled walks, 50.1% of ambiguous decisions occur at depth 2, 25.0% at depth 3, 12.5% at depth 4, and 12.4% at depth 5 or greater. Consequently, only 12.4% of ambiguous decisions are stored in the main configuration. The average required history is approximately 21 bits, although the unrestricted worst case can require 263 stored decisions for the 533-step schedule. A stack of 60 decision bits is allocated, with overflow treated as a rare failure event having probability $2.4\times10^{-6}$ per inversion.

During forward execution, the parity bit $b$ controls the arithmetic update. Stored decisions are pushed onto the history stack. Decoded decisions are subjected to measurement-based uncomputation in the $X$ basis. The measurement removes the qubit but leaves a phase dependent on $b$ and the measurement result. During reverse execution, the decoder reconstructs $b$, applies the corresponding phase correction, and uses the restored $g$ parity to clear the residual branch information. The reverse step either pops a stored decision or reconstructs one from the updated arithmetic state before applying the inverse divstep transformation.

The arithmetic transformations, determinant identity, and branch-decoding rules are exact. Failures arise from deliberately bounded resource limits rather than approximation of the divstep algebra.

The architecture also packs data into two 256-qubit registers rather than maintaining four permanent 256-bit registers. One register shares storage between $g$ and $f_v$; the other shares storage between $f$ and $g_v$. Remainder-like values shrink while coefficient-like values grow, allowing growing coefficients to occupy positions vacated by shrinking remainders. The widths and locations are fixed when the circuit is generated; inputs exceeding those assigned widths count as failures.

## 5. Termination, scale removal, and prime-specific arithmetic

The circuit schedules 533 divstep positions, although the mathematical worst-case bound is 590 active steps. It freezes a walk when $g=0$ using a frozen flag and a step-index register. Because a frozen state is identical at every later scheduled step, the state alone does not reveal when freezing began. The expensive zero test is enabled only after step 498, and the circuit accepts failures for walks that terminate before the zero-test window, fail to terminate by the end of the schedule, or overflow counters and integer widths.

Sampled stopping times are concentrated roughly between steps 505 and 530. The reported early-stopping probability is approximately $1.4\times10^{-6}$ per inversion, while the $z$-register overflow probability is approximately $9\times10^{-8}$ per inversion.

The input-dependent factor $2^{-t}$ is removed during reverse execution rather than by retaining the active-step count. If the desired result is $aw^{-1}$, termination produces

$$
r=af_v\equiv2^taw^{-1}\pmod p.
$$

Each active reverse step performs modular halving:

$$
r\mapsto
\begin{cases}
r/2,&r\text{ even},\\[1mm]
(r+p)/2,&r\text{ odd}.
\end{cases}
$$

The frozen flag identifies active reverse steps. After exactly $t$ halvings, the result is $aw^{-1}\pmod p$, while the walk registers are restored and no explicit stopping-time register remains.

The sparse form of the secp256k1 prime enables specialized reduction:

$$
2^{256}\equiv2^{32}+977\pmod p.
$$

High product bits can therefore be folded into low bits using the small constant $2^{32}+977$. The point adder fuses coordinate arithmetic into destination registers, avoids materializing a complete $\lambda^2$ register, and splits

$$
\lambda=\lambda_0+2^{128}\lambda_1
$$

so that

$$
\lambda^2
=
\lambda_0^2
+
2^{129}\lambda_0\lambda_1
+
2^{256}\lambda_1^2
\pmod p.
$$

The three products are accumulated and cleared one at a time.

Carry propagation is truncated within the permitted failure budget. Modular-reduction carries propagate through only the low 58 bits, or 60 bits in the fused square, and comparison tests inspect only the top 27 bits. These truncations are resource-limited approximations in the complete circuit and are distinct from the exact divstep identities.

## 6. Resource frontier, comparisons, and limitations

The main architecture is embedded in a complete reversible affine point adder implementing

$$
\lvert P\rangle\longmapsto\lvert P+Q\rangle,
$$

with a classically supplied addend $Q$, cleaned ancillas, and the correct phase except on a specified bounded fraction of inputs. Its resource counts are

$$
T=4.0\times10^6\text{ Toffolis},
\qquad
Q=935\text{ qubits},
$$

with

$$
TQ\approx3.7\times10^9.
$$

The four divstep walks contribute approximately $2.5\times10^6$ Toffolis, or 63% of the total. Surrounding field multiplication contributes $1.4\times10^6$ Toffolis, or 35%, while fused square and coordinate additions contribute approximately $0.10\times10^6$.

The history-decoding threshold produces an explicit Toffoli–qubit trade-off.

| Configuration | Toffolis | Qubits |
|---|---:|---:|
| Larger-history / lower-decoding-cost | $3.6\times10^6$ | 1,031 |
| Main $j_{\mathrm{store}}=5$ configuration | $4.0\times10^6$ | 935 |
| Low-qubit $j_{\mathrm{store}}=9$ configuration | $7.9\times10^6$ | 893 |
| Higher-qubit configuration | $3.3\times10^6$ | 1,191 |

At $j_{\mathrm{store}}=0$, every ambiguous decision is stored, requiring approximately 198 history qubits and producing a total of 1,065 qubits. At $j_{\mathrm{store}}=9$, decoders handle depths through 8, leaving 24 history qubits and producing the lowest-qubit point reported.

The divstep construction is not the lowest-Toffoli point-adder construction in the reported comparison. A binary-gcd construction with a dialog/history trick uses approximately $1.9\times10^6$ Toffolis and 1,446 qubits. The discovered divstep circuit uses more Toffolis but fewer qubits. Packed Euclidean approaches use 838 to 843 qubits but require approximately $2.1\times10^7$ to $7.0\times10^7$ Toffolis.

A second discovered construction specializes a packed Euclidean walk to the secp256k1 modulus. It uses $20.5\times10^6$ Toffolis and 843 qubits, compared with a reconstructed baseline using $69.5\times10^6$ Toffolis and 838 qubits. The specialization reduces Toffoli count by a factor of approximately 3.4 at the cost of five qubits. The divstep architecture is therefore the lower-Toffoli alternative among the two discovered constructions, whereas the specialized Euclidean architecture occupies the extreme low-qubit end.

The permitted failure probability is approximately $2\times10^{-4}$ per point addition. The reported union-bound contributions are:

| Failure source | Probability per point addition |
|---|---:|
| Multiplier carry and comparison truncation | $7.07\times10^{-5}$ |
| Stopping-time and integer-size limits | $7.56\times10^{-5}$ |
| Early stopping and $z$-register limits | $6.18\times10^{-6}$ |
| Branch-history overflow | $6.8\times10^{-6}$ |
| Fused-square carry limit | $6\times10^{-7}$ |
| Union bound | $1.599\times10^{-4}$ |

In 100,000 random tests of the full point-addition circuit, four failures were observed. The point-addition input distribution samples $P$ and $Q$ independently and nearly uniformly from curve points, excluding affine-formula exceptional cases. For a 16-bit-window algorithm invoking the point adder 28 times, a union bound gives less than 0.6% retry overhead.

The primary score is $TQ$, with Toffoli and CCZ gates counted equally. This metric is a convenient uniform objective rather than a universal hardware criterion. Toffoli depth, active volume, magic-state throughput, or a more heavily qubit-weighted objective could be more appropriate under other fault-tolerant architectures. No complete modular-inversion circuit-depth or Toffoli-depth estimate is reported.

## 7. LLM-guided discovery and broader significance

The architecture was discovered through evolutionary search over Python programs that construct circuits rather than through ordinary gate-level peephole optimization. Candidate programs contain named quantum registers, reusable arithmetic functions, loops, control logic, ancilla allocation and freeing, reversible gates, measurement-based uncomputation, and the overall algorithmic organization.

The search procedure provided a hand-written task specification, requested several algorithm families from a large language model, evolved each family independently, periodically shared strong candidates across families, tested candidates with an independent evaluator, and retained valid circuits according to their resource scores. The search used OpenEvolve with Claude Mythos 5 and MAP-Elites. MAP-Elites preserved different points in the $(T,Q)$ resource plane rather than only the single minimum-$TQ$ candidate.

The evaluator checked basis-state input/output relations, preservation of input registers, phase correctness, cleanup of all ancillas, measurement-record independence of the logical permutation, Toffoli count, and peak qubit count. The circuit model permits reversible classical gates, diagonal sign gates, and destructive $X$-basis measurements with phase correction. A candidate is valid only if every ancilla returns to $\lvert0\rangle$ and the measurement record factors from the logical output. The simulator follows computational-basis trajectories rather than full amplitudes because the allowed gates preserve computational-basis states up to phase.

The significance of the divstep result lies in its reversible architecture and representation rather than in a local gate rewrite. The current arithmetic state acts as a compressed, partially decodable record of the execution history. The determinant and scaling invariants provide global constraints, while the $2$-adic structure of the coefficient registers supplies local branch information. Explicit history is retained only where decoding becomes more expensive than storage.

The construction demonstrates that divsteps, previously impractical for reversible integer arithmetic under a straightforward implementation, can be incorporated into a reversible prime-field inversion circuit for the secp256k1 benchmark. Its scope is nevertheless constrained by the prime-specific sparse reduction, the assumed input distribution, bounded failure probability, fitted stopping-time and carry limits, selected resource objective, and extensive state-decoding logic. It establishes a viable benchmark architecture rather than a universal result that divsteps dominates binary-gcd or Euclidean inversion for all moduli, operand sizes, or fault-tolerant hardware models.

Source: https://www.emergentmind.com/topics/divsteps