Code example: Quantum full adder

What is the quantum full adder

Just like in classical electronics, where you can make different types of binary adders like half adders, full adders, ripple carry adders etcetera, you can make adders in quantum circuis as well. In this example we will show how a quantum full adder is created and how this adder acts on superposition states.

The full adder adds to input bits A and B plus a carry_input bit and produces the sum and carry_output bits as output. In classical control electronics the full adder has therefore three inputs and four outputs.

Since quantum circuits are reversible, they have an equal amount of input and output qubits, therefore we define a 4-qubit function, where the input qubits are A,B, CarryIn and (zero) and the output qubits are A,B, Sum and CarryOut, see the figure below.

One possible implementation of a 2-bit full adder, using CNOT gates and Toffoli gates is the following:

For completeness we show the truth table for the full adder:

Inputs: q0 = A ; q1 = B ; q2= CarryIn

Outputs: q0 = A ; q1 = B ; q2= SumOut ; q3 = CarryOut

. q3 q2 q1 q0 . q3 q2 q1 q0
. . Ci B A . Co S B A
. . . . . . . . . .
T1 0 0 0 0 - 0 0 0 0
T2 0 1 0 0 - 0 1 0 0
T3 0 0 1 0 - 0 1 1 0
T4 0 1 1 0 - 1 0 1 0
T5 0 0 0 1 - 0 1 0 1
T6 0 1 0 1 - 1 0 0 1
T7 0 0 1 1 - 1 0 1 1
T8 0 1 1 1 - 1 1 1 1

How does it work

The code below shows what happens when we use the quantum full adder to add three qubit states. You can copy and paste this code in your own editor and see what happens when you change the input states A, B and CarryIn to either $\left\lvert 0 \right\rangle$ or $\left\lvert 1 \right\rangle$ using the X-gate in the initialization function. In this example we set A = 1, B = 0 and CarryIn = 1, equal to T6 in the truth table.

Examination of the code and results

When we execeute the code, setting the number of shots to 1, we get the histogram as shown below the code, which is equal to the exepected output (compare to T6 in the truth table). Note: one shot is enough to determine the probabiliity distribution

Version 1.0

qubits 4

# name qubits
map q,qA
map q,qB
map q,CarryIn_SumOut
map q,CarryOut

# init inputs to some values
.init
#initialize inputs 0 en 1 to a Bell state and carry_in to a superposition state
{x q | x q}

toffoli q,q,q
cnot    q,q
toffoli q,q,q
cnot    q,q
cnot    q,q

We can also use superposition states and entangled states, such as in the following code where we set A and B to a Bell state and CarryIn to a superposition state. This is similar to setting the input to states T1, T2, T7 and T8 at the same time.

Comparing again the truth table to the historgram of probability amplitudes, we indeed see that all 4 output states that we would expect are generated.

Want to know more?

In this example we showed how to create a simple quantum full adder. In the literature you can find other examples to add qubit states, subtract qubit states and execute more complex operations on qubit states.