This is a revised edition. Two points have been corrected from the initial version.
- How to read the measurement results. In the current blueqat (2.1.3), the rightmost character of the measurement result string corresponds to the 0th qubit (explained in Part 2)
- The way to implement step 4, where N is conditionally added back, has been revised to match Fig. 4 of the paper. This eliminates the need for 3-controlled gates and ancilla qubits, reducing the number of qubits from 4n+3 to 4n+2.
Introduction
In Part 2, we built a standard quantum adder. This time, we implement modular addition a + b mod N on top of it.
The intermediate values generated during the computation of a^j mod N must all be kept within the range [0, N), which is why this is the actual addition used in Shor's algorithm.
The reference is Vedral, Barenco, Ekert, "Quantum Networks for Elementary Arithmetic Operations" (1995), specifically Fig. 4 (Section III.B of the paper).
The 5-Step Concept
(a+b) mod N is simple classically: add them, and if the result is greater than or equal to N, subtract N by that amount.
However, a quantum computer cannot "branch after checking." Checking requires measurement, which would destroy the delicate superposition. Instead, we record the check in a qubit and express the conditional branching in the form of the circuit.
- Addition: b ← a + b (The adder from Part 2)
- Subtract N: b ← b - N (Execute the adder in reverse)
- Sign detection: If b becomes negative in step 2, the topmost extra qubit in the b register becomes 1 (the borrow/overflow flag). Copy this to a flag qubit t.
- Conditionally add back N: If t=1 (meaning a+b < N and we subtracted too much), add N back. However, only for the branches in superposition where t=1.
- Cleanup: Reset t to |0⟩ and undo the sign detection step. This makes the entire circuit a reusable operation that leaves no trace other than in b.
The assumption is 0 ≤ a, b < N. Steps 1–2 simply use the adder and subtractor as they are. The interesting part is step 4; in the initial version, I implemented this part differently from the paper.
Reusing Components from Part 2
We reuse carry / carry_inv / sum_gate from Part 2 as-is, and restructure the adder into add_circuit, which takes registers from outside and returns only the circuit. Its inverse operation is sub_circuit.
from blueqat import Circuit
def carry(c, a, b, c_next):
circ = Circuit()
circ.ccx[a, b, c_next]
circ.cx[a, b]
circ.ccx[c, b, c_next]
return circ
def carry_inv(c, a, b, c_next):
circ = Circuit()
circ.ccx[c, b, c_next]
circ.cx[a, b]
circ.ccx[a, b, c_next]
return circ
def sum_gate(c, a, b):
circ = Circuit()
circ.cx[a, b]
circ.cx[c, b]
return circ
def add_circuit(c, a, b, n):
"""b := a + b. Uses carry register c. b has n+1 qubits."""
circ = Circuit()
for i in range(n - 1):
circ += carry(c[i], a[i], b[i], c[i + 1])
circ += carry(c[n - 1], a[n - 1], b[n - 1], b[n])
circ.cx[a[n - 1], b[n - 1]]
circ += sum_gate(c[n - 1], a[n - 1], b[n - 1])
for i in range(n - 2, -1, -1):
circ += carry_inv(c[i], a[i], b[i], c[i + 1])
circ += sum_gate(c[i], a[i], b[i])
return circ
def sub_circuit(c, a, b, n):
"""b := b - a. Just reverses the entire sequence of gates in the adder."""
add_circ = add_circuit(c, a, b, n)
reversed_circ = Circuit()
reversed_circ.ops = list(reversed(add_circ.ops))
return reversed_circsub_circuit only requires "executing the same sequence of gates in reverse" because the gates used here are only CX and CCX, both of which are self-inverse. There is no need to invert individual gates. The paper also states this ("an adder whose network is run backwards").
How to Implement Step 4
How do we implement "execute b ← b + N only when t=1"?
Initial Version's Approach (Different from the Paper)
Straightforwardly, this means controlling all gates of add_circuit(c, N, b, n) with t. Controlling CX makes it CCX, which is easy, but controlling CCX requires a 3-controlled X gate, which has no direct corresponding gate in the SDK.
Therefore, in the initial version, I introduced a decomposition using one ancilla qubit: compute the first 2-controlled AND into the ancilla bit using CCX, use it for control, and then uncompute it back using another CCX. I introduced this as a "trap."
The Paper's Approach
However, the relevant section of the paper says something completely different.
Conditionally on the value of this last qubit |t⟩, N is added back to the second register, leaving it with the value a + b mod N. This is done by either leaving the first register with the value N (in case of overflow), or resetting it to 0 (if there is no overflow) and then using a plain adder.
Do not touch the adder. Instead, make the N register (which holds the number to be added) conditional. If t=1, keep N as is; if t=0, reset it to 0 and pass it through a plain adder.
Why does this work? Because adding 0 does nothing. We can run the adder unconditionally; if the input is 0, it will act as an identity transformation automatically.
When you want to "perform an operation only on branches with superposition," instead of making the operation conditional, make the input conditional so that the operation becomes trivial. This is a common and effective idea in reversible computation. The paper uses this same trick in the next section on controlled multiplication (Fig. 5).
What is decisive is that this approach never introduces a 3-controlled gate. The "trap" in the initial version was caused by our own implementation choices. No ancilla qubits are needed either.
Making the N Register Conditionally Zero
N is a classical constant known at the time the circuit is constructed, so we know which bits are 1. We just apply a 0-controlled CNOT (with X gates sandwiching t) to the bits of N that are set to 1.
def set_to_zero_if(t, N, val_N, n):
"""Reset the N register to 0 if t=0 (keep it as is if t=1). Self-inverse."""
circ = Circuit()
circ.x[t]
for j in range(n):
if (val_N >> j) & 1:
circ.cx[t, N[j]]
circ.x[t]
return circSince X and CX are self-inverse and their targets are distinct, running this circuit again restores N to its original state. "Apply, use, and undo with the same thing"—this is the simplest form of uncomputation that appeared in Part 2.
Register Configuration
The entire modular adder uses 4n+2 qubits (the initial version used 4n+3).
c[0..n-1]: Carry register (shared during addition/subtraction steps)a[0..n-1]: First addendb[0..n]: Second addend and result (n+1 width. In step 3, the most significant bit also serves as the overflow flag)N[0..n-1]: Modulus (read as a constant)t: A single flag indicating "whether N needed to be added back"
The removal of ancilla qubits is the key change in this revision.
Full Code for the Modular Adder
def build_modulo_adder(input_a, input_b, input_N, n):
"""b := (a + b) mod N. Returns (circuit, index of b)."""
num_qubits = 4 * n + 2
circ = Circuit(num_qubits)
c = list(range(n))
a = list(range(n, 2 * n))
b = list(range(2 * n, 3 * n + 1))
N = list(range(3 * n + 1, 4 * n + 1))
t = 4 * n + 1
# Encoding inputs
for i in range(n):
if (input_a >> i) & 1: circ.x[a[i]]
if (input_b >> i) & 1: circ.x[b[i]]
if (input_N >> i) & 1: circ.x[N[i]]
# Steps 1-2: b <- a + b, then b <- b - N
circ += add_circuit(c, a, b, n)
circ += sub_circuit(c, N, b, n)
# Step 3: Copy the borrow/overflow bit to flag t
circ.cx[b[n], t]
# Step 4: If t=0, set N register to 0, pass through uncontrolled adder, restore N
gate = set_to_zero_if(t, N, input_N, n)
circ += gate
circ += add_circuit(c, N, b, n)
circ += gate
# Step 5: Cleanup. Undo sign detection and restore t to |0>
circ += sub_circuit(c, a, b, n)
circ.x[b[n]]
circ.cx[b[n], t]
circ.x[b[n]]
circ += add_circuit(c, a, b, n)
return circ, bStep 4 is now just 3 lines. There is no need to iterate through the contents of add_circuit gate by gate and rewrite them as in the initial version.
Testing
Here is the execution function. Since the rightmost character of the measurement result corresponds to the 0th qubit, we read it as state[total - 1 - q].
def run_modulo_adder(val_a, val_b, val_N, n=None):
if n is None:
n = max(val_N, 1).bit_length()
circuit, b = build_modulo_adder(val_a, val_b, val_N, n)
state = circuit.m[:].run(shots=1, backend='statevector').most_common(1)[0][0]
total = circuit.n_qubits
bits = [state[total - 1 - q] for q in b] # bits[0] is the least significant bit
return int("".join(reversed(bits)), 2)
tests = [(7, 6, 11, 4), (14, 13, 15, 4), (3, 5, 9, 4), (0, 0, 7, 3), (5, 5, 6, 3)]
for x, y, N, n in tests:
result = run_modulo_adder(x, y, N, n)
expected = (x + y) % N
print(f"({x}+{y}) mod {N} = {result} (Expected {expected}, "
f"{'OK' if result == expected else 'MISMATCH'})")(7+6) mod 11 = 2 (Expected 2, OK)
(14+13) mod 15 = 12 (Expected 12, OK)
(3+5) mod 9 = 8 (Expected 8, OK)
(0+0) mod 7 = 0 (Expected 0, OK)
(5+5) mod 6 = 4 (Expected 4, OK)The key point is explicitly specifying
backend='statevector'. Since blueqat's default backend operates via tensor network contraction, the cost is determined not by the number of qubits but by the connection structure of the circuit. This type of circuit, which has few qubits but is deep, is not well-suited for it. In the next multiplication circuit, it ran out of memory with fewer than 20 qubits. With the statevector backend, the memory consumption is straightforwardly determined by 2^(number of qubits).
Let's also look at boundary values: cases where a+b is exactly N (result is 0), one operand is 0, and both are maximum.
(4+3) mod 7 = 0 (Expected 0, OK)
(10+10) mod 11 = 9 (Expected 9, OK)
(0+5) mod 9 = 5 (Expected 5, OK)
(6+6) mod 7 = 5 (Expected 5, OK)
(8+9) mod 10 = 7 (Expected 7, OK)Exhaustive Test
For N = 5, 7, 9, we test all possible combinations of a and b. Moreover, we verify not only the result in b, but also that the N register, flag t, and carry register c are all restored to their original states.
If working bits do not return to |0⟩, they remain entangled with the result, destroying subsequent quantum interference. The modular adder is a component that will be reused dozens of times in the next and following articles, so we cannot afford to miss a single case here.
def run_and_check(val_a, val_b, val_N, n=None):
if n is None:
n = max(val_N, 1).bit_length()
circuit, b = build_modulo_adder(val_a, val_b, val_N, n)
c = list(range(n)); N = list(range(3 * n + 1, 4 * n + 1)); t = 4 * n + 1
state = circuit.m[:].run(shots=1, backend='statevector').most_common(1)[0][0]
total = circuit.n_qubits
read = lambda qs: int("".join(reversed([state[total - 1 - q] for q in qs])), 2)
clean = read(N) == val_N and int(state[total - 1 - t]) == 0 and read(c) == 0
return read(b), clean
bad = 0
for N in (5, 7, 9):
for a in range(N):
for b in range(N):
result, clean = run_and_check(a, b, N)
if result != (a + b) % N or not clean:
bad += 1
print(f"MISMATCH ({a}+{b})%{N} -> {result}, clean={clean}")
print(f"{bad} mismatches out of 155 cases")0 mismatches out of 155 casesAll cases passed.
Note from the Editorial Department: We verified this on our site
We verified the code in this article using blueqat 2.1.3. Since the circuit consists only of X, CX, and CCX gates, the results can be verified accurately by tracking each qubit as a classical bit (0 or 1) one gate at a time. All 10 cases in the article and all 155 exhaustive test cases were correct, and the N register, flag t, and carry were all restored. There were zero mismatches for all cases with N = 2–33 (expanding the range). The number of qubits, gates, and maximum control number are shown in the table below.
The Three Traps, Revisited
In the initial version, I introduced three points I encountered during implementation as "traps." Here is the evaluation after the revision:
Trap ①: To find the inverse operation, you must also reverse the order of gates — This is Real
When creating a subtractor, simply replacing carry with carry_inv internally is not enough. You must reverse the entire sequence of gates. In reversible computation, the "inverse of a circuit" means applying the inverse of each gate in reverse order. Since the gates here are self-inverse, only the ordering matters.
This aligns with the paper, and can be written in one line using list manipulation list(reversed(...)).
Trap ②: Lack of Multi-controlled Gates — This was Self-Inflicted
The issue was that blueqat lacks CCCX (a gate controlling CCX). I substituted it with ancilla bits and Toffoli chains.
This is not a trap, but a design mistake on our part. If we implement step 4 as described in the paper, 3-controlled gates never appear. The maximum number of Toffoli (CCX) gates in the entire circuit is limited, and the number of ancilla qubits is zero.
Simply using the obvious fact that "adding 0 is the identity transformation" completely eliminates the need for multi-controlled gates. Only by implementing it did I finally understand why the 1995 paper chose this form.
Trap ③: The Position of X Gates — This is Also Real
In step 5, when resetting the flag t to |0⟩:
circ.x[b[n]]
circ.cx[b[n], t]
circ.x[b[n]]If you omit one of the Xs, the condition is inverted, and t is not cleared. This is used to create a 0-controlled CNOT, depicted as a small white circle in the paper's figure. You must pay attention to the distinction between white and black circles in the paper's diagrams.
Note that after the revision, the same "sandwiched by X" pattern appears in set_to_zero_if in step 4. Once you get used to it, you can read it as a standard idiom.
Number of Qubits and Gates
| n | Qubits | Gate Count | Max Control |
|---|---|---|---|
| 3 | 14 | 124 | 2 |
| 4 | 18 | 166 | 2 |
| 8 | 34 | 334 | 2 |
| 16 | 66 | 670 | 2 |
The gate count is given for the case where all bits of N are 1 (the maximum case). It does not include the X gates used to write the input. Depending on N, up to 2n gates can be fewer than this count.
Both the number of qubits and the number of gates are linear with respect to n. This matches the paper's statement: "the number of elementary gates in the plain adder, the modular addition ... scales linearly with n."
The biggest achievement of the revision is that the maximum control number remains 2 regardless of how large n gets.
Summary
- (a+b) mod N consists of 5 steps: "Add → Subtract N → Check for overflow → Conditionally add back → Cleanup"
- Subtraction is simply achieved by reversing the entire gate sequence of the adder
- For the conditional addition back, do not control the adder; instead, conditionally set the N register to 0. Since adding 0 is an identity transformation, the adder can be run unconditionally
- This eliminates the need for gates exceeding Toffoli or ancilla qubits. It fits within 4n+2 qubits
- Whether working bits return to |0⟩ must be tested as strictly as the final result values
- In the current blueqat, the rightmost character of the measurement string is qubit 0
Next Time Preview
Now that we have addition and modular addition, the next step is controlled modular multiplication. Multiply a constant a by a quantum-controlled value modulo N. It is a reversible long multiplication that repeatedly adds shifted copies of the multiplicand via modular addition.
The same trick as this time—"making the input conditional so that the operation becomes trivial"—will appear once again there.