Skip to content

Instantly share code, notes, and snippets.

@lnikon
Created March 9, 2021 15:59
Show Gist options
  • Save lnikon/4391ed1240712b7b2204d61d554c396b to your computer and use it in GitHub Desktop.
Save lnikon/4391ed1240712b7b2204d61d554c396b to your computer and use it in GitHub Desktop.
Quantum Full Adder
from qiskit import QuantumCircuit, assemble, Aer
from qiskit.visualization import plot_histogram
A = 0
B = 1
XOR_A_B = 2
SUM = 4
CARRY_IN = 3
AND_A_B = 5
CARRY_OUT = 6
# Number of the qubits in the circuit.
n = 7
# Number of the outputs.
out = 2
qc_fa = QuantumCircuit(n,out)
qc_fa.x(A)
# qc_fa.x(B)
# qc_fa.x(CarryIn)
qc_fa.barrier()
# Compute XOR(A,B) and write result onto wire 2
qc_fa.cx(A,XOR_A_B)
qc_fa.cx(B,XOR_A_B)
# Compute XOR(Carry-In, XOR(A,B)) and write result onto wire 4.
# Output of this part will be the sum.
qc_fa.cx(XOR_A_B,SUM)
qc_fa.cx(CARRY_IN,SUM)
# Compute Carry-Out.
# Compute AND(A,B).
qc_fa.ccx(A,B,AND_A_B)
# Compute AND(XOR(A,B), Carry-In).
qc_fa.ccx(XOR_A_B,CARRY_IN,CARRY_OUT)
qc_fa.barrier()
qc_fa.measure(SUM,0)
qc_fa.measure(CARRY_OUT,1)
qc_fa.draw()
@DavitKhach
Copy link

I have added these lines at the end of the code and checked the solution.

from qiskit import execute
simulator = Aer.get_backend('qasm_simulator')
job = execute(qc_fa, simulator, shots=1000)
result = job.result()
counts = result.get_counts(qc_fa)
print(counts)

For input

qc_fa.x(A)
qc_fa.x(B)

The code's output is '00' instead of '10'. I think the problem is in the calculation of the CARRY-OUT.

@DavitKhach
Copy link

This line should be added at the end

qc_fa.cx(AND_A_B,CARRY_OUT)

Because when A = 1 and B = 1, XOR_A_B = 0 and the last ccx(XOR_A_B , ...) will not work and Carry_out will be equal to 0, but should equal to 1. For A = 1 and B = 1, we can add one more cx controlled by AND_A_B and the problem will be solved. If XOR_A_B = 1 only ccx will work, if AND_A_B = 1 only newly added cx will work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment