News

日本語 · English · 中文

[Guest Contribution] Learning Shor’s Algorithm from Scratch (Part 2): Auto-generating Quantum Adders with the blueqat SDK

Building a quantum adder, the foundation of Shor’s algorithm, with the blueqat SDK. It uses 3n+1 qubits for n-bit addition, generating carries in the forward pass and eliminating them during the backward pass to determine the sum. This article also explains how to interpret measurement results in the current version of blueqat (2.1.3), verifying that it works correctly across all 5,460 cases.

In Part 1, we organized the overall flow of Shor’s algorithm and identified the roles of the quantum circuits. Starting this issue, we will actually construct quantum circuits using Python.

First, we will verify the behavior of the basic gates (X, CX, CCX), which form the foundation of all computations, and then build a quantum adder (Plain Adder). The method for constructing the circuit follows the paper by Vedral, Barenco, and Ekert: Quantum Networks for Elementary Arithmetic Operations (arXiv:quant-ph/9511018).

Preparation

We use the blueqat SDK to describe quantum circuits.

pip install git+https://github.com/blueqat/blueqatSDK

The code in this article was run with blueqat version 2.1.3 installed via this method.

Three Basic Gates

The computation in Shor’s algorithm, when broken down, leads to standard logical operations: NOT, XOR, and AND. In quantum circuits, these are represented by the following three gates:

  • X gate (NOT): Flips the bit.
  • CX gate (CNOT, corresponding to XOR): Flips the target bit only if the control bit is 1.
  • CCX gate (Toffoli, corresponding to AND): Flips the target bit only when both control bits are 1.
from blueqat import Circuit

def measure(circuit):
    """Runs the circuit once and returns the measurement result string (the rightmost bit is qubit 0)."""
    result = circuit.m[:].run(shots=1, backend='statevector')
    return result.most_common(1)[0][0]

print("X   : |0> ->", measure(Circuit(1).x[0]))
print("X   : |1> ->", measure(Circuit(1).x[0].x[0]))
print("CX  : Control 0 ->", measure(Circuit(2).cx[0, 1]))
print("CX  : Control 1 ->", measure(Circuit(2).x[0].cx[0, 1]))
print("CCX : Control is 1 for q0 only ->", measure(Circuit(3).x[0].ccx[0, 1, 2]))
print("CCX : Controls q0 and q1 are both 1 ->", measure(Circuit(3).x[0].x[1].ccx[0, 1, 2]))
X   : |0> -> 1
X   : |1> -> 0
CX  : Control 0 -> 00
CX  : Control 1 -> 11
CCX : Control is 1 for q0 only -> 001
CCX : Controls q0 and q1 are both 1 -> 111

Reading Measurement Results

In blueqat version 2.1.3, the measurement result string has the rightmost bit as qubit 0. Therefore, 001 above means "only q0 is 1," and since only one control bit is 1, the CCX gate performs no operation. 111 is the result of q2 being flipped because both controls were 1.

The bit ordering differs by SDK; even for blueqat, the order is reversed between versions (the PyPI version 2.0.4 has the leftmost bit as qubit 0). To be sure, check which end produces a 1 when you apply x[0] only once in your environment.

Design of the Quantum Adder

Next, we look at the quantum adder in Figure 1 of the paper. All computations used in Shor’s algorithm are constructed using this adder as a component.

Assembly of a quantum adder. An n-bit addition uses 3n+1 qubits. It generates carries on the forward path and eliminates them on the reverse path while determining the sum.
Assembly of a quantum adder. An n-bit addition uses 3n+1 qubits. It generates carries on the forward path and eliminates them on the reverse path while determining the sum.

When adding numbers in a quantum circuit, carry information is generated in the process. If this carry information is left as is, those qubits remain entangled with the inputs, interfering with the interference of superpositions in subsequent stages. Therefore, we treat the process up to resetting the carries to 0 after addition (uncomputing) as a single circuit.

Qubit Allocation

An addition of n-bit numbers uses 3n + 1 qubits.

  • Carry c (n qubits): Indices 0 to n−1
  • Addend a (n qubits): Indices n to 2n−1
  • Augend b (n+1 qubits): Indices 2n to 3n. The result goes here. The last qubit, 3n (denoted as b_n in the paper), is the location for the most significant carry.

Procedure

  • Forward path (CARRY): From the least significant bit upwards, use CCX to "create the carry for the next bit c_{i+1} from a_i and b_i (and the carry from the lower bit)." For the most significant bit, write instead of c into b_n.
  • Turnaround: Determine the sum of the most significant bit using SUM. Before that, re-apply the CX gate that the most significant CARRY applied to b, to reverse it (for lower bits, the inverse circuit of CARRY performs this role).
  • Reverse path (Inverse CARRY + SUM): Going backwards from the most significant bit, use the inverse of the CARRY circuit to reset carries c to 0, while writing the sum of each bit to b using SUM.

Code for the Quantum Adder

We create a function that determines the number of bits based on input size, constructs the circuit, runs it once, and converts the answer back to decimal. In future parts, we will reuse this circuit as a component for modular adders and multipliers.

from blueqat import Circuit

def carry(c, a, b, c_next):
    """CARRY: Generates the carry for this bit in 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):
    """Inverse of CARRY (gates arranged in reverse order). Eliminates the carry."""
    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):
    """SUM: Writes the sum a XOR b XOR c for this bit to b"""
    circ = Circuit()
    circ.cx[a, b]
    circ.cx[c, b]
    return circ

def build_adder(val_a, val_b, n):
    """Constructs a circuit to compute b := a + b. Returns (circuit, qubit indices for b)."""
    circ = Circuit(3 * n + 1)
    c = list(range(n))                  # Carry      0 .. n-1
    a = list(range(n, 2 * n))           # Addend a   n .. 2n-1
    b = list(range(2 * n, 3 * n + 1))   # Augend b   2n .. 3n (b[n] is the most significant carry)

    for i in range(n):                  # Write inputs
        if (val_a >> i) & 1: circ.x[a[i]]
        if (val_b >> i) & 1: circ.x[b[i]]

    for i in range(n - 1):              # Forward path: Generate carries from the least significant bit
        circ += carry(c[i], a[i], b[i], c[i + 1])
    circ += carry(c[n - 1], a[n - 1], b[n - 1], b[n])   # Most significant carry goes to b[n]

    circ.cx[a[n - 1], b[n - 1]]         # Reverse the CX applied by the most significant CARRY to b
    circ += sum_gate(c[n - 1], a[n - 1], b[n - 1])

    for i in range(n - 2, -1, -1):      # Reverse path: Eliminate carries while determining sums
        circ += carry_inv(c[i], a[i], b[i], c[i + 1])
        circ += sum_gate(c[i], a[i], b[i])
    return circ, b

def add(val_a, val_b):
    n = max(val_a, val_b, 1).bit_length()          # Ensure registers are not empty even if 0 is passed
    circ, b = build_adder(val_a, val_b, n)
    state = circ.m[:].run(shots=1, backend='statevector').most_common(1)[0][0]
    total = circ.n_qubits
    bits = [state[total - 1 - q] for q in b]       # Rightmost bit is qubit 0
    return int("".join(reversed(bits)), 2), state, n

answer, state, n = add(10, 6)
print(f"a = 10, b = 6, n = {n}, Number of qubits = {3 * n + 1}")
print(f"Measurement result (rightmost is qubit 0): {state}")
print(f"Answer: {answer}")

for x, y in [(1, 1), (3, 5), (7, 9), (15, 15), (0, 0)]:
    print(f"{x} + {y} = {add(x, y)[0]}")
a = 10, b = 6, n = 4, Number of qubits = 13
Measurement result (rightmost is qubit 0): 1000010100000
Answer: 16
1 + 1 = 2
3 + 5 = 8
7 + 9 = 16
15 + 15 = 30
0 + 0 = 0

10 + 6 = 16 (10000 in binary) was correctly calculated in a 13-qubit circuit.

Two Things Read from the Results

Why shots=1 is Sufficient

Many quantum algorithms yield probabilistic answers, requiring thousands of executions to obtain a distribution. However, this adder uses only X, CX, and CCX gates. These are gates that merely "swap 0 and 1," and like classical logic circuits, if the input is determined, the output is uniquely determined. Therefore, the answer is fixed with a single measurement.

The Clean Elimination of Carries

Reading the measurement result 1000010100000 from the right end (qubit 0), the first four characters (the four carries c) are all 0. Bits that should have been 1 due to carries during computation have returned to their original state of 0.

This is the effect of applying the inverse CARRY circuit from the most significant bit downwards during the reverse path. This leaves only the answer in b and returns the intermediate bits to a state unentangled with the inputs. This "undoing after use" (uncomputation) is indispensable for computing while maintaining superposition in subsequent parts.

Just to be safe, we have verified that the answers are correct and carries return to 0 for all combinations of bit counts n = 1 to 6 (5,460 cases).

Next Time: Modular Adder

This adder becomes a subtractor simply by arranging all gates in reverse order. This is because X, CX, and CCX are all gates that return to their original state when applied twice.

Next time, we will create a modular adder (Adder modulo N) by combining addition and subtraction ("subtract N if the result is N or more"). The next topic will be how to implement "if-then" logic in quantum circuits.

This article was translated from the Japanese original. 日本語で読む

← Latest articles