# Tutorial: Implement Grover's search algorithm in Q#

In this tutorial, you can learn how to build and run Grover search to speed up the search of unstructured data. Grover's search is one of the most popular quantum computing algorithms, and this relatively small Q# implementation gives you a sense of some of the advantages of programming quantum solutions with a high-level Q# quantum programming language to express quantum algorithms. At the end of the guide, you will see the simulation output demonstrates successfully finding a specific string among a list of unordered entries in a fraction of the time it would take to search the whole list on a classical computer.

Grover's algorithm searches a list of unstructured data for specific items. For example, it can answer the question: Is this card drawn from a pack of cards an ace of hearts? The labeling of the specific item is called *marked input*.

Using Grover's search algorithm, a quantum computer is guaranteed to run this search in fewer steps than the number of items in the list that you're searching — something no classical algorithm can do. The increased speed in the case of a pack of cards is negligible; however, in lists containing millions or billions of items, it becomes significant.

You can build Grover's search algorithm with just a few lines of code.

## Prerequisites

- The Microsoft Quantum Development Kit.

## What does Grover's search algorithm do?

Grover's algorithm asks whether an item in a list is the one we are searching for. It does this by constructing a quantum superposition of the indexes of the list with each coefficient, or probability amplitude, representing the probability of that specific index being the one you are looking for.

At the heart of the algorithm are two steps that incrementally boost the coefficient of the index that we are looking for, until the probability amplitude of that coefficient approaches one.

The number of incremental boosts is fewer than the number of items in the list. This is why Grover's search algorithm performs the search in fewer steps than any classical algorithm.

## Write the code

Using the Quantum Development Kit, create a new Q# project for the command line application. Title the project

`Grover`

.Add the following code to the

`Program.qs`

file in your new project:`namespace Microsoft.Quantum.Samples.SimpleGrover { open Microsoft.Quantum.Convert; open Microsoft.Quantum.Math; open Microsoft.Quantum.Arrays; open Microsoft.Quantum.Measurement; /// # Summary /// This operation applies Grover's algorithm to search all possible inputs /// to an operation to find a particular marked state. @EntryPoint() operation SearchForMarkedInput(nQubits : Int) : Result[] { using (qubits = Qubit[nQubits]) { // Initialize a uniform superposition over all possible inputs. PrepareUniform(qubits); // The search itself consists of repeatedly reflecting about the // marked state and our start state, which we can write out in Q# // as a for loop. for (idxIteration in 0..NIterations(nQubits) - 1) { ReflectAboutMarked(qubits); ReflectAboutUniform(qubits); } // Measure and return the answer. return ForEach(MResetZ, qubits); } } /// # Summary /// Returns the number of Grover iterations needed to find a single marked /// item, given the number of qubits in a register. function NIterations(nQubits : Int) : Int { let nItems = 1 <<< nQubits; // 2^numQubits // compute number of iterations: let angle = ArcSin(1. / Sqrt(IntAsDouble(nItems))); let nIterations = Round(0.25 * PI() / angle - 0.5); return nIterations; } }`

To define the list that we're searching, create a new file

`Reflections.qs`

, and paste in the following code:`namespace Microsoft.Quantum.Samples.SimpleGrover { open Microsoft.Quantum.Intrinsic; open Microsoft.Quantum.Convert; open Microsoft.Quantum.Math; open Microsoft.Quantum.Canon; open Microsoft.Quantum.Arrays; open Microsoft.Quantum.Measurement; /// # Summary /// Reflects about the basis state marked by alternating zeros and ones. /// This operation defines what input we are trying to find in the main /// search. operation ReflectAboutMarked(inputQubits : Qubit[]) : Unit { Message("Reflecting about marked state..."); using (outputQubit = Qubit()) { within { // We initialize the outputQubit to (|0⟩ - |1⟩) / √2, // so that toggling it results in a (-1) phase. X(outputQubit); H(outputQubit); // Flip the outputQubit for marked states. // Here, we get the state with alternating 0s and 1s by using // the X instruction on every other qubit. ApplyToEachA(X, inputQubits[...2...]); } apply { Controlled X(inputQubits, outputQubit); } } } /// # Summary /// Reflects about the uniform superposition state. operation ReflectAboutUniform(inputQubits : Qubit[]) : Unit { within { // Transform the uniform superposition to all-zero. Adjoint PrepareUniform(inputQubits); // Transform the all-zero state to all-ones PrepareAllOnes(inputQubits); } apply { // Now that we've transformed the uniform superposition to the // all-ones state, reflect about the all-ones state, then let // the within/apply block transform us back. ReflectAboutAllOnes(inputQubits); } } /// # Summary /// Reflects about the all-ones state. operation ReflectAboutAllOnes(inputQubits : Qubit[]) : Unit { Controlled Z(Most(inputQubits), Tail(inputQubits)); } /// # Summary /// Given a register in the all-zeros state, prepares a uniform /// superposition over all basis states. operation PrepareUniform(inputQubits : Qubit[]) : Unit is Adj + Ctl { ApplyToEachCA(H, inputQubits); } /// # Summary /// Given a register in the all-zeros state, prepares an all-ones state /// by flipping every qubit. operation PrepareAllOnes(inputQubits : Qubit[]) : Unit is Adj + Ctl { ApplyToEachCA(X, inputQubits); } }`

The

`ReflectAboutMarked`

operation defines the marked input that you are searching for: the string of alternating zeros and ones. This sample hard-codes the marked input, and can be extended to search for different inputs or generalized for any input.Next, run your new Q# program to find the item marked by

`ReflectAboutMarked`

.

### Q# command line applications with Visual Studio or Visual Studio Code

The executable will run the operation or function marked with the `@EntryPoint()`

attribute on a simulator or resource estimator, depending on the project configuration and command-line options.

In Visual Studio, simply press Ctrl + F5 to execute the script.

In VS Code, build the `Program.qs`

the first time by typing the below in the terminal:

```
dotnet build
```

For subsequent runs, there is no need to build it again. To run it, type the following command and press enter:

```
dotnet run --no-build
```

You should see the following message displayed in the terminal:

```
operations.qs:
This operation applies Grover's algorithm to search all possible inputs to an operation to find a particular marked state.
Usage:
operations.qs [options] [command]
--n-qubits <n-qubits> (REQUIRED)
-s, --simulator <simulator> The name of the simulator to use.
--version Show version information
-?, -h, --help Show help and usage information
Commands:
```

This is because you didn't specify the number of qubits you wanted to use, so the terminal tells you the commands available for the executable. If we want to use 5 qubits we should type:

```
dotnet run --n-qubits 5
```

Pressing enter you should see the following output:

```
Reflecting about marked state...
Reflecting about marked state...
Reflecting about marked state...
Reflecting about marked state...
[Zero,One,Zero,One,Zero]
```

## Next steps

If you enjoyed this tutorial, check out some of the resources below to learn more about how you can use Q# to write your own quantum applications:

- Back to the Getting Started with QDK guide
- Try a more general Grover's search algorithm sample
- Learn more about Grover's search with the Quantum Katas
- Read more about Amplitude amplification, the quantum computing technique behind Grover's search algorithm
- Quantum computing concepts
- Quantum Development Kit Samples