Skip to content

Commit 2fc165b

Browse files
abhishekjiitrgithub-actions
and
github-actions
authored
Qiskit: Add Quantum Half Adder (TheAlgorithms#3405)
* Qiskit: Add Quantum Half Adder * fixup! Format Python code with psf/black push Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
1 parent fb655f7 commit 2fc165b

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

Diff for: quantum/half_adder.py

+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
#!/usr/bin/env python3
2+
"""
3+
Build a half-adder quantum circuit that takes two bits as input,
4+
encodes them into qubits, then runs the half-adder circuit calculating
5+
the sum and carry qubits, observed over 1000 runs of the experiment
6+
.
7+
8+
References:
9+
- https://en.wikipedia.org/wiki/Adder_(electronics)
10+
- https://qiskit.org/textbook/ch-states/atoms-computation.html#4.2-Remembering-how-to-add-
11+
"""
12+
13+
import qiskit as q
14+
15+
16+
def half_adder(bit0: int, bit1: int) -> q.result.counts.Counts:
17+
"""
18+
>>> half_adder(0, 0)
19+
{'00': 1000}
20+
>>> half_adder(0, 1)
21+
{'01': 1000}
22+
>>> half_adder(1, 0)
23+
{'01': 1000}
24+
>>> half_adder(1, 1)
25+
{'10': 1000}
26+
"""
27+
# Use Aer's qasm_simulator
28+
simulator = q.Aer.get_backend("qasm_simulator")
29+
30+
qc_ha = q.QuantumCircuit(4, 2)
31+
# encode inputs in qubits 0 and 1
32+
if bit0 == 1:
33+
qc_ha.x(0)
34+
if bit1 == 1:
35+
qc_ha.x(1)
36+
qc_ha.barrier()
37+
38+
# use cnots to write XOR of the inputs on qubit2
39+
qc_ha.cx(0, 2)
40+
qc_ha.cx(1, 2)
41+
42+
# use ccx / toffoli gate to write AND of the inputs on qubit3
43+
qc_ha.ccx(0, 1, 3)
44+
qc_ha.barrier()
45+
46+
# extract outputs
47+
qc_ha.measure(2, 0) # extract XOR value
48+
qc_ha.measure(3, 1) # extract AND value
49+
50+
# Execute the circuit on the qasm simulator
51+
job = q.execute(qc_ha, simulator, shots=1000)
52+
53+
# Return the histogram data of the results of the experiment.
54+
return job.result().get_counts(qc_ha)
55+
56+
57+
if __name__ == "__main__":
58+
counts = half_adder(1, 1)
59+
print(f"Half Adder Output Qubit Counts: {counts}")

0 commit comments

Comments
 (0)