|
| 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 |
0 commit comments