Skip to content

Commit b8db80d

Browse files
committed
berstein-vazirani algorithm
1 parent 28a8692 commit b8db80d

File tree

3 files changed

+60
-1
lines changed

3 files changed

+60
-1
lines changed

Bernstein-Vazirani Algorithm.py

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
'''
2+
Bernstein-Vazirani Algorithm
3+
4+
We know that an oracle function f is implemented like this
5+
6+
f : {0, 1}^n -> {0, 1}
7+
8+
f(x) = a x
9+
10+
Task: Find a.
11+
12+
'''
13+
from qiskit import IBMQ, BasicAer
14+
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
15+
16+
qr = QuantumRegister(4) # Initialize qubits
17+
cr = ClassicalRegister(4) # Initialize bits for record measurements
18+
circuit = QuantumCircuit(qr, cr)
19+
20+
circuit.x(qr[3]) # initialize the ancilla qubit in the |1> state
21+
22+
# First step of quantum algorithms - Prepare the superposition
23+
# For superposition, we apply the Hadamard gate on all qubits
24+
circuit.h(qr[0])
25+
circuit.h(qr[1])
26+
circuit.h(qr[2])
27+
circuit.h(qr[3])
28+
29+
# Oracle function
30+
circuit.cx(qr[0], qr[3])
31+
circuit.cx(qr[1], qr[3])
32+
circuit.cx(qr[2], qr[3])
33+
34+
# Apply Hadamard gates after querying oracle function
35+
circuit.h(qr[0])
36+
circuit.h(qr[1])
37+
circuit.h(qr[2])
38+
circuit.h(qr[3])
39+
40+
# Measure qubit
41+
circuit.measure(qr[0], cr[0])
42+
circuit.measure(qr[1], cr[1])
43+
circuit.measure(qr[2], cr[2])
44+
45+
# Run our circuit with local simulator
46+
backend = BasicAer.get_backend('qasm_simulator')
47+
shots = 1024
48+
results = execute(circuit, backend=backend, shots=shots).result()
49+
answer = results.get_counts()
50+
print("Simulator result")
51+
for c2c1c0 in answer:
52+
print(f"{c2c1c0} is observed in {answer[c2c1c0]} times")
53+
# 0111 observed in 1024 times
54+
# 0111 in base 2 = 7 in base 10
55+
# hence, a = 7

README.md

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,8 @@ Quantum computing examples with Qiskit.
99

1010
**Deutsch-Jozsa Algorithm**
1111

12-
![Deutsch-Jozsa Algorithm](./circuit_diagrams/02_deutsch_jozsa.png)
12+
![Deutsch-Jozsa Algorithm](./circuit_diagrams/02_deutsch_jozsa.png)
13+
14+
**Bernstein-Vazirani Algorithm**
15+
16+
![Bernstein-Vazirani Algorithm](./circuit_diagrams/03_bernstein_vazirani.png)
19.2 KB
Loading

0 commit comments

Comments
 (0)