|
| 1 | +''' |
| 2 | + Grover's algorithm |
| 3 | +
|
| 4 | + For given an oracle function f : {0, 1}^n -> {0, 1}^n, ∃! ω : f(ω) = a, |
| 5 | + find ω. |
| 6 | +
|
| 7 | + Although the purpose of Grover's algorithm is usually described as "searching a database", |
| 8 | + it may be more accurate to describe it as "inverting a function". Roughly speaking, if we |
| 9 | + have a function y=f(x) that can be evaluated on a quantum computer, Grover's algorithm |
| 10 | + allows us to calculate x when given y. Inverting a function is related to the searching of |
| 11 | + a database because we could come up with a function that produces a particular value of y |
| 12 | + if x matches a desired entry in a database, and another value of y for other values of x. |
| 13 | +
|
| 14 | + Source: https://www.quantiki.org/wiki/grovers-search-algorithm |
| 15 | +
|
| 16 | +''' |
| 17 | +from qiskit import IBMQ, BasicAer |
| 18 | +from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute |
| 19 | + |
| 20 | +qr = QuantumRegister(3) # Initialize qubits |
| 21 | +cr = ClassicalRegister(3) # Initialize bits for record measurements |
| 22 | +circuit = QuantumCircuit(qr, cr) |
| 23 | + |
| 24 | +# We want to search two marked states |
| 25 | +# |101> and |110> |
| 26 | + |
| 27 | +# Apply Hadamard to all qubits |
| 28 | +circuit.h(qr) |
| 29 | +circuit.barrier() |
| 30 | + |
| 31 | +# Phase oracle (Marks states |101> and |110> as results) |
| 32 | +circuit.cz(qr[2], qr[0]) |
| 33 | +circuit.cz(qr[2], qr[1]) |
| 34 | + |
| 35 | +# Inversion around the average |
| 36 | +circuit.h(qr) |
| 37 | +circuit.x(qr) |
| 38 | +circuit.barrier() |
| 39 | +circuit.h(qr[2]) |
| 40 | +circuit.ccx(qr[0], qr[1], qr[2]) |
| 41 | +circuit.h(qr[2]) |
| 42 | +circuit.barrier() |
| 43 | +circuit.x(qr) |
| 44 | +circuit.h(qr) |
| 45 | + |
| 46 | +# Measure |
| 47 | +circuit.measure(qr, cr) |
| 48 | + |
| 49 | +# Run our circuit with local simulator |
| 50 | +backend = BasicAer.get_backend('qasm_simulator') |
| 51 | +shots = 1024 |
| 52 | +results = execute(circuit, backend=backend, shots=shots).result() |
| 53 | +answer = results.get_counts() |
| 54 | +print(answer) |
0 commit comments