## Introduction

Classically, searching an unsorted database requires a linear search, which is *O(N)* in time. Grover’s algorithm, which takes *O(N1/2)* time, is the fastest possible quantum algorithm for searching an unsorted database. It provides “only” a quadratic speedup, unlike other quantum algorithms, which can provide exponential speedup over their classical counterparts. However, even quadratic speedup is considerable when *N* is large.

Like all quantum computer algorithms, Grover’s algorithm is probabilistic, in the sense that it gives the correct answer with high probability. The probability of failure can be decreased by repeating the algorithm.

## Uses of Grover's algorithm

Although the purpose of Grover’s algorithm is usually described as “searching a database”, it may be more accurate to describe it as “inverting a function”. Roughly speaking, if we have a function *y=f(x)* that can be evaluated on a quantum computer, Grover’s algorithm allows us to calculate *x* when given *y*. Inverting a function is related to the searching of a database because we could come up with a function that produces a particular value of *y* if *x* matches a desired entry in a database, and another value of *y* for other values of *x*.

Grover’s algorithm can also be used for estimating the mean and median of a set of numbers, and for solving the collision problem. In addition, it can be used to solve NP-complete problems by performing exhaustive searches over the set of possible solutions. This would result in a considerable speedup over classical solutions, even though it does not provide the “holy grail” of a polynomial-time solution.

Below, we present the basic form of Grover’s algorithm, which searches for a single matching entry. The algorithm can be further optimized if there is more than one matching entry and the number of matches is known beforehand.

## Implementation

You will need an API token which you can get by registering here: https://quantum-computing.ibm.com/

from qiskit import IBMQ, BasicAer

from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, executeqr = QuantumRegister(3) # Initialize qubits

cr = ClassicalRegister(3) # Initialize bits for record measurements

circuit = QuantumCircuit(qr, cr)# We want to search two marked states

# |101> and |110># Apply Hadamard to all qubits

circuit.h(qr)

circuit.barrier()# Phase oracle (Marks states |101> and |110> as results)

circuit.cz(qr[2], qr[0])

circuit.cz(qr[2], qr[1])# Inversion around the average

circuit.h(qr)

circuit.x(qr)

circuit.barrier()

circuit.h(qr[2])

circuit.ccx(qr[0], qr[1], qr[2])

circuit.h(qr[2])

circuit.barrier()

circuit.x(qr)

circuit.h(qr)# Measure

circuit.measure(qr, cr)# Run our circuit with local simulator

backend = BasicAer.get_backend('qasm_simulator')

shots = 1024

results = execute(circuit, backend=backend, shots=shots).result()

answer = results.get_counts()

print(answer)