|
| 1 | +''' |
| 2 | + Bernstein-Vazirani Algorithm |
| 3 | +
|
| 4 | + We know that an oracle function f which has period a: |
| 5 | +
|
| 6 | + f : {0, 1}^n -> {0, 1}^n |
| 7 | +
|
| 8 | + ∃!a != 0: ∀x f(x) = f(y) => y = x ⊕ a |
| 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 | +# First two qubits form a register to store x, last two qubits from a register to store f(x) |
| 21 | +# Apply Hadamard to first two |
| 22 | +circuit.h(qr[0]) |
| 23 | +circuit.h(qr[1]) |
| 24 | + |
| 25 | +circuit.barrier() |
| 26 | + |
| 27 | +# Oracle function, a = 11 |
| 28 | +circuit.cx(qr[0], qr[2]) |
| 29 | +circuit.cx(qr[1], qr[2]) |
| 30 | +circuit.cx(qr[0], qr[3]) |
| 31 | +circuit.cx(qr[1], qr[3]) |
| 32 | + |
| 33 | +circuit.barrier() |
| 34 | + |
| 35 | +# Measure last two qubits |
| 36 | +circuit.measure(qr[2], cr[2]) |
| 37 | +circuit.measure(qr[3], cr[3]) |
| 38 | + |
| 39 | +circuit.barrier() |
| 40 | + |
| 41 | +# Apply Hadamard to first two qubits |
| 42 | +circuit.h(qr[0]) |
| 43 | +circuit.h(qr[1]) |
| 44 | + |
| 45 | +circuit.barrier() |
| 46 | + |
| 47 | +circuit.measure(qr[0], cr[0]) |
| 48 | +circuit.measure(qr[1], cr[1]) |
| 49 | + |
| 50 | +# Run our circuit with local simulator |
| 51 | +backend = BasicAer.get_backend('qasm_simulator') |
| 52 | +shots = 1024 |
| 53 | +results = execute(circuit, backend=backend, shots=shots).result() |
| 54 | +answer = results.get_counts() |
| 55 | + |
| 56 | +# Categorize measurements by input register values |
| 57 | +answer_plot = {} |
| 58 | +for measresult in answer.keys(): |
| 59 | + measresult_input = measresult[2:] |
| 60 | + if measresult_input in answer_plot: |
| 61 | + answer_plot[measresult_input] += answer[measresult] |
| 62 | + else: |
| 63 | + answer_plot[measresult_input] = answer[measresult] |
| 64 | + |
| 65 | +print(answer_plot) |
| 66 | + |
| 67 | + |
| 68 | +def sdotz(a, b): # Calculate the dot product of the results |
| 69 | + accum = 0 |
| 70 | + for i in range(len(a)): |
| 71 | + accum += int(a[i]) * int(b[i]) |
| 72 | + return (accum % 2) |
| 73 | + |
| 74 | + |
| 75 | +print('s, z, s.z (mod 2)') |
| 76 | +for z_rev in answer_plot: |
| 77 | + z = z_rev[::-1] |
| 78 | + print(f'{11}, {z}, {11}.{z}={sdotz("11",z)}') |
| 79 | +# We can recover the value of a = 11. |
0 commit comments