Level 6 · Practitioner’s Corner
Grover’s Algorithm in Qiskit: Build, Run and Tune the Search
About 5,003 words · roughly 23 minute read · sources checked December 2, 2026
Grover’s algorithm is the best-known quantum speed-up that is also small enough to run by hand. On two qubits it finds the marked item with certainty after one step. On three qubits, one marked item among eight, the success chance rises to 78% after one iteration, 94.5% after two, and then falls to 33% after three. That rise and fall is the single most important thing to understand about the algorithm, and Qiskit lets you watch it happen.
This lesson is the hands-on companion to the concept lesson on Grover’s algorithm. It assumes you have read “Your First Qiskit Circuit” and know what a circuit, a measurement and the Sampler are. Here you will build the oracle and the diffuser out of ordinary gates, run the search, and check every probability against a calculation.
A note on honesty. Qiskit was not installed in my working environment, so I could not run any of the code below. I wrote it from the documented behaviour that the first lesson relied on, and I computed every number with my own NumPy simulation of the same gates, using Qiskit’s documented bit ordering (qubit 0 is the rightmost character of a result string). Run the code and compare. If something differs, trust your run, check your Qiskit version, and tell me.
What you will learn
- How to build a phase oracle that marks one bitstring, using X gates and a controlled-Z.
- How to build the diffuser (the “inversion about the mean”) from H, X and a controlled-Z.
- The exact success probability after k iterations, and the formula behind it.
- Why running too many iterations makes the answer worse.
- What changes when more than one item is marked.
- How the iteration count grows for large search spaces, and what that means for real hardware.
Helpful first: Your First Qiskit Circuit, Grover’s Algorithm.
The idea in one paragraph
You have N possible answers and a way to recognise the right one when you see it, but no clue where it is. A classical computer checks them one at a time, so it needs about N/2 checks on average. Grover’s algorithm starts with an equal superposition of all N answers, then repeats two moves. The first, the oracle, flips the sign of the marked answer’s amplitude. The second, the diffuser, reflects every amplitude about the average, which makes the marked amplitude bigger and the others smaller. About (π/4)√N repeats are enough.
Notice what the algorithm does not do. It does not look at all N answers at once and report the right one. Measuring gives only one bitstring, and the whole algorithm is a way of arranging the amplitudes so that the right bitstring is the likely result. The concept lesson explains why; here we make it concrete.
What “marked” means in code
In this lesson the oracle is built so that it flips the sign of exactly one bitstring that we choose in advance. In a real search problem the oracle would be a circuit that checks a condition (a valid password, a satisfying assignment) without anyone knowing the answer. Building an oracle that does that cheaply is usually the hard part, and the speed-up only counts if the oracle itself is cheap.
Step 1: Grover on two qubits
Two qubits give N = 4 answers: 00, 01, 10, 11. We will mark 11. Start with the full program, then go through it.
from qiskit import QuantumCircuit
from qiskit.primitives import StatevectorSampler
qc = QuantumCircuit(2)
# 1. equal superposition of all four answers
qc.h([0, 1])
# 2. oracle: flip the sign of |11>
qc.cz(0, 1)
# 3. diffuser: reflect about the average
qc.h([0, 1])
qc.x([0, 1])
qc.cz(0, 1)
qc.x([0, 1])
qc.h([0, 1])
qc.measure_all()
sampler = StatevectorSampler()
counts = sampler.run([(qc, None, 1024)]).result()[0].data.meas.get_counts()
print(counts) # expected: {'11': 1024}In my simulation the final state has all of its probability on 11: P(11) = 1.0 and the other three outcomes have probability 0. So with an exact simulator every one of the 1,024 shots should be 11. On a real, noisy device you would see some other bitstrings too, and we return to that later.
Why one controlled-Z is the oracle
A controlled-Z applies a Z gate to one qubit if the other is 1. Z leaves |0⟩ alone and flips the sign of |1⟩, so the pair of qubits picks up a minus sign only when both are 1. That is exactly “flip the sign of |11⟩”. For any other two-bit answer you first use X gates to turn that answer into 11, apply the controlled-Z, then undo the X gates.
Worked example
Following the amplitudes by hand
- After the first layer of Hadamards, each of the four answers has amplitude 1/2. Their average is 1/2.
- The oracle flips the sign of |11⟩. Amplitudes are now (1/2, 1/2, 1/2, −1/2) for (00, 01, 10, 11). The average is (3/2 − 1/2)/4 = 1/4.
- The diffuser reflects each amplitude about the average: new = 2 × average − old. That gives 2(1/4) − 1/2 = 0 for the first three, and 2(1/4) − (−1/2) = 1 for |11⟩.
- So the state is exactly |11⟩, with probability 1. This is why two qubits need only one iteration: with N = 4 and one marked item, a single step lands on the answer.
That “reflect about the average” step is the geometric heart of the algorithm. The diffuser in the code, H then X then controlled-Z then X then H, is a standard way to build that reflection from basic gates. The details of why that circuit does it are in the concept lesson.
Step 2: marking a different answer
To search for a different bitstring, change the oracle only. Wrap the controlled-Z in X gates on every qubit whose target bit is 0, so that the target becomes 11 before the controlled-Z and is restored after it.
def oracle_2q(qc, target): # target is a string such as '10'
bits = target[::-1] # bits[i] is the value for qubit i
for i, b in enumerate(bits):
if b == '0':
qc.x(i)
qc.cz(0, 1)
for i, b in enumerate(bits):
if b == '0':
qc.x(i)The reversal line is the one that trips people up. Qiskit prints bitstrings with qubit 0 on the right. If you want to mark the string 10, qubit 1 must be 1 and qubit 0 must be 0, so you need an X gate on qubit 0. Reading the string left to right and applying X to index 0 would flip the wrong qubit and mark 01 instead.
| Target string | Qubit 1 | Qubit 0 | X gates needed | P(target) after 1 iteration | P(each other string) |
|---|---|---|---|---|---|
| 11 | 1 | 1 | none | 1.0 | 0.0 |
| 10 | 1 | 0 | on qubit 0 | 1.0 | 0.0 |
| 01 | 0 | 1 | on qubit 1 | 1.0 | 0.0 |
| 00 | 0 | 0 | on qubits 0 and 1 | 1.0 | 0.0 |
My simulation, which gave probability 1.0 for the target in all four cases after exactly one iteration.
Test the ordering before trusting it
A one-minute check settles any doubt about bit order: run the circuit for a target such as 10 and see whether the output is 10 or 01. If it is the wrong way round, your oracle is marking the mirror-image string. The first lesson used the same trick with a single X gate.
Step 3: three qubits, where iteration count matters
With three qubits there are N = 8 answers, and one iteration is no longer enough. The oracle now needs a controlled-controlled-Z, which Qiskit provides as the ccz method. The diffuser has the same shape as before, with one more qubit.
from qiskit import QuantumCircuit
from qiskit.primitives import StatevectorSampler
def grover_3q(target, iterations):
bits = target[::-1] # bits[i] belongs to qubit i
qc = QuantumCircuit(3)
qc.h([0, 1, 2])
for _ in range(iterations):
# oracle: flip the sign of the target string
for i, b in enumerate(bits):
if b == '0':
qc.x(i)
qc.ccz(0, 1, 2)
for i, b in enumerate(bits):
if b == '0':
qc.x(i)
# diffuser
qc.h([0, 1, 2])
qc.x([0, 1, 2])
qc.ccz(0, 1, 2)
qc.x([0, 1, 2])
qc.h([0, 1, 2])
qc.measure_all()
return qc
sampler = StatevectorSampler()
for k in range(0, 4):
qc = grover_3q('101', k)
counts = sampler.run([(qc, None, 4096)]).result()[0].data.meas.get_counts()
print(k, counts.get('101', 0) / 4096)The loop at the bottom prints the fraction of shots that landed on 101 for k = 0, 1, 2, 3 iterations. In my simulation the exact probabilities are:
| Iterations k | P(101) | P(each of the other seven) | Expected count of 101 in 4,096 shots |
|---|---|---|---|
| 0 | 0.1250 | 0.1250 | 512 |
| 1 | 0.7813 | 0.0313 | 3,200 |
| 2 | 0.9453 | 0.0078 | 3,872 |
| 3 | 0.3301 | 0.0957 | 1,352 |
From my NumPy simulation of the circuit above. The expected counts are 4,096 times the probability; real runs will scatter around them.
Read the table slowly. With no iterations, the answer is no better than a guess (1/8). One iteration lifts it to 78%. Two lift it to 94.5%. A third iteration, which sounds like more of a good thing, drops it to 33%. The algorithm overshoots.
This is the point of the whole lesson
Grover’s algorithm is not “keep going until it works”. There is a right number of iterations, and a different number gives a worse answer. If you run too few, you waste the speed-up. If you run too many, you rotate past the answer. For one marked item among N the best count is close to (π/4)√N, which for N = 8 is 2.22, so you round to 2.
The formula behind the table
Each iteration rotates the state by a fixed angle in a two-dimensional picture whose axes are “the marked item” and “everything else”. If there are M marked items among N, define the angle θ by sin θ = √(M/N). After k iterations the probability of measuring a marked item is sin²((2k + 1)θ).
Worked example
Checking the formula against the table
- N = 8 and M = 1, so sin θ = 1/√8 = 0.35355 and θ = 0.36137 radians (20.7°).
- k = 1: (2 × 1 + 1)θ = 3θ = 1.0841 radians, and sin²(1.0841) = 0.78125. This matches 0.7813.
- k = 2: 5θ = 1.8068 radians, and sin² = 0.94531. This matches 0.9453.
- k = 3: 7θ = 2.5296 radians, and sin² = 0.33008. This matches 0.3301, and it is lower because 7θ has gone past 90° (1.5708 radians).
The same formula explains the two-qubit result. With N = 4 and M = 1, sin θ = 1/2, so θ = 30° and 3θ = 90°, giving sin²(90°) = 1. One iteration lands exactly on the answer. A second iteration would rotate on to 150°, where sin² is 0.25, which is what my simulation gave.
What if more than one answer is marked?
The oracle can mark several bitstrings at once, and the same formula applies with M greater than 1. More marked items means a larger angle, so you need fewer iterations, and you can overshoot sooner. Here is the pattern for N = 8, computed from the formula and checked against my simulation for M = 1 and M = 2.
| Marked items M | k = 0 | k = 1 | k = 2 | k = 3 |
|---|---|---|---|---|
| 1 | 0.125 | 0.781 | 0.945 | 0.330 |
| 2 | 0.250 | 1.000 | 0.250 | 0.250 |
| 3 | 0.375 | 0.844 | 0.023 | 0.990 |
| 4 | 0.500 | 0.500 | 0.500 | 0.500 |
Success probability sin²((2k+1)θ) with sin θ = √(M/8). Rows M = 1 and M = 2 match my simulation; M = 3 and M = 4 are from the formula alone.
Two rows deserve a comment. With M = 2 one iteration is perfect, because θ = 30° just as in the two-qubit case. With M = 4, half of all answers are marked, θ = 45°, and every iteration leaves the probability at 0.5, so the algorithm gives no help at all: guessing already succeeds half the time.
You must know roughly how many items are marked
The best iteration count depends on M. If you do not know M, you can run the algorithm with several different iteration counts, or use a related technique called quantum counting to estimate M first. Running a fixed number of iterations blindly can land on a bad one, as the M = 3 row shows: k = 2 gives a probability of 0.023, while k = 3 gives 0.990.
How the iteration count grows
The reason Grover’s algorithm matters is how slowly the count grows. Each extra qubit doubles N, but the number of iterations grows only by a factor of √2, about 1.41.
| Qubits n | N = 2ⁿ | Classical checks (average, about N/2) | Grover iterations, about (π/4)√N |
|---|---|---|---|
| 4 | 16 | 8 | 3 |
| 10 | 1,024 | 512 | 25 |
| 20 | 1,048,576 | 524,288 | 804 |
| 30 | 1,073,741,824 | 536,870,912 | 25,736 |
Computed with (π/4)√N rounded to the nearest whole number. Each Grover iteration also costs one call to the oracle and a diffuser.
A quadratic speed-up like this is real, but it is a modest one compared with the exponential claims people sometimes make. It turns a billion checks into about twenty-six thousand. That is a big saving on paper. The catch is cost per iteration: each one needs a full oracle circuit and a diffuser, run on qubits that are noisy, and a long sequence of gates has a low chance of finishing without an error. The cost-of-a-quantum-computer and error-correction lessons on this site explain why this matters.
A practical warning
A circuit with about 26,000 iterations of an oracle that itself has many gates would need far more error-free operations than any device today can run without error correction. The small examples in this lesson run on a simulator, and on real hardware only the smallest cases give clean answers.
Running it on a noisy device
On a real quantum computer the result is not exact. Gates have errors and measurements sometimes misread. For the two-qubit example, the ideal outcome is 11 on every shot. A real device will return mostly 11, with some 00, 01 and 10. How many depends on the machine, and I do not give a figure because I did not run it on one.
There is a way to judge the result without a hardware run. Imagine each shot is independently correct with probability q and otherwise lands on one of the other three strings at random. The expected count of the target in S shots is Sq, with a spread of √(Sq(1 − q)). For example, for a 4,096-shot run with q = 0.9453 (the ideal three-qubit k = 2 value), the expected count is 3,872 and the spread is about 14.6 shots, so ordinary runs should fall within roughly 3,840 to 3,900 in an ideal simulator.
Worked example
Spread of the three-qubit counts
- S = 4,096 and q = 0.94531 give an expected count of 4,096 × 0.94531 = 3,872.
- The standard deviation is √(4,096 × 0.94531 × 0.05469) = √211.8 = 14.55.
- So with an ideal simulator the printed value should be about 0.945, with random scatter of roughly ±0.0036 (one standard deviation, 14.55 ÷ 4,096).
When you move the same circuit to hardware, expect the fraction on the target to fall below that ideal. Transpiling for a device also changes the circuit, because real devices support only certain gates. The lesson “From Simulator to Real Hardware” covers that step.
Step 4: four and five qubits
For more than three qubits you need a multi-controlled Z. A simple way to build one in Qiskit is to sandwich a multi-controlled X between two Hadamards on the last qubit, because H X H equals Z. The method for the multi-controlled X is mcx, which takes a list of control qubits and a target.
def mcz(qc, n):
qc.h(n - 1)
qc.mcx(list(range(n - 1)), n - 1) # controls: all qubits except the last
qc.h(n - 1)
def grover(n, target, iterations):
bits = target[::-1]
qc = QuantumCircuit(n)
qc.h(range(n))
for _ in range(iterations):
for i, b in enumerate(bits):
if b == '0': qc.x(i)
mcz(qc, n)
for i, b in enumerate(bits):
if b == '0': qc.x(i)
qc.h(range(n)); qc.x(range(n))
mcz(qc, n)
qc.x(range(n)); qc.h(range(n))
qc.measure_all()
return qcThe probabilities from my simulation, using the target 0110 for four qubits and 01101 for five, are:
| Iterations k | n = 4 (N = 16): P(target) | n = 5 (N = 32): P(target) |
|---|---|---|
| 0 | 0.0625 | 0.0312 |
| 1 | 0.4727 | 0.2583 |
| 2 | 0.9084 | 0.6024 |
| 3 | 0.9613 | 0.8969 |
| 4 | 0.5817 | 0.9992 |
| 5 | 0.1255 | 0.8596 |
| 6 | 0.0204 | 0.5459 |
Exact probabilities from my simulation. Best choice: k = 3 for four qubits (formula (π/4)√16 = 3.14) and k = 4 for five qubits ((π/4)√32 = 4.44, rounded down here because k = 4 gives 0.9992 while k = 5 gives 0.8596).
For five qubits the formula’s value of 4.44 rounds to 4, and the table confirms that 4 is the best whole number: 0.9992, nearly certain. Going to 5 or 6 iterations visibly loses ground. The rule is a good guide, and for small N it is worth checking the exact sine formula before you decide.
Cost grows with the multi-controlled gate
A controlled-Z on many qubits is not a single native gate on real devices. It is broken into many one- and two-qubit gates, and the number grows with the number of controls. This is one reason that Grover circuits on real hardware are much deeper than the diagrams suggest.
Run Grover's algorithm in your browser
Here are three small searches you can run right now on this site's simulator. The marked item is the bitstring 101 for three qubits and 11 for two. As always, predict the result before pressing Run. The strings follow Qiskit's bit order, with qubit 0 as the rightmost bit.
Four items, one iteration
Run this circuit
Grover on two qubits: one iteration is exact
Bit order: q0 is the rightmost digit of each result, as in Qiskit. All qubits start in |0⟩ unless marked. This is an ideal simulator with no hardware noise.
Press Run to simulate. Results appear here with a short explanation.
Eight items: one, two and three iterations
Run this circuit
Grover, 3 qubits, one iteration
Bit order: q0 is the rightmost digit of each result, as in Qiskit. All qubits start in |0⟩ unless marked. This is an ideal simulator with no hardware noise.
Press Run to simulate. Results appear here with a short explanation.
Run this circuit
Grover, 3 qubits, two iterations
Bit order: q0 is the rightmost digit of each result, as in Qiskit. All qubits start in |0⟩ unless marked. This is an ideal simulator with no hardware noise.
Press Run to simulate. Results appear here with a short explanation.
Run this circuit
Grover, 3 qubits, three iterations (overshoot)
Bit order: q0 is the rightmost digit of each result, as in Qiskit. All qubits start in |0⟩ unless marked. This is an ideal simulator with no hardware noise.
Press Run to simulate. Results appear here with a short explanation.
Compare the three eight-item runs. One iteration finds 101 about 78 percent of the time, two iterations about 94.5 percent, and three iterations only about 33 percent. More work made the answer worse. This surprises people the first time, and it is the most important practical fact about Grover's algorithm: you must stop at the right iteration.
The success probability, exactly
With one marked item among N, define the angle θ by sin θ = 1/√N. After k iterations the probability of measuring the marked item is sin²((2k + 1)θ). The state moves around a circle by 2θ per iteration, and the probability is the squared height of the state on the marked axis, so it climbs to a peak and then falls again. The table lists the values I computed from this formula.
| Items N | θ (radians) | k = 0 | k = 1 | k = 2 | k = 3 | k = 4 | k = 5 |
|---|---|---|---|---|---|---|---|
| 4 | 0.5236 | 0.2500 | 1.0000 | 0.2500 | 0.2500 | ||
| 8 | 0.3614 | 0.1250 | 0.7813 | 0.9453 | 0.3301 | 0.0122 | |
| 16 | 0.2527 | 0.0625 | 0.4727 | 0.9084 | 0.9613 | 0.5817 | 0.1255 |
| 64 | 0.1253 | 0.0156 | 0.1348 | 0.3439 | 0.5914 | 0.8164 | 0.9635 |
Success probability sin²((2k + 1)θ) for one marked item. My own calculation from the formula; empty cells are beyond the useful range.
For N = 4 one iteration gives probability exactly 1, because θ = 30 degrees and the state lands on the marked axis at 90 degrees. For N = 8 the best choice is k = 2, with probability 0.9453, and for N = 16 the best is k = 3 at 0.9613. For N = 64 the best is k = 6, probability 0.9966.
optimal k ≈ (π / 4)·√N − 1/2, rounded down N = 8: (π/4)·2.83 = 2.22 → k = 2 N = 64: (π/4)·8 = 6.28 → k = 6 N = 1,048,576: (π/4)·1024 = 804.25 → k = 804, success 1.0000
A million items need about 804 iterations, where a classical search needs about half a million checks on average. This is the quadratic speed-up in numbers. Notice also how the gain grows: at N = 64 the quantum side takes 6 iterations against 32 classical checks on average, a saving of about five times, and at N = 2²⁰ the saving is more than six hundred times, consistent with √N growth.
What noise does: stop earlier
The ideal table assumes perfect gates. On real hardware each gate adds a small chance of error, and each Grover iteration is long, because the three-qubit oracle and diffuser both contain a Toffoli-type gate. To see how this plays out, I wrote a NumPy density-matrix simulation of the three-qubit search. The Toffoli is decomposed into six CNOT gates plus single-qubit gates in the standard way, and I checked numerically that the decomposition equals the Toffoli. After every gate the simulation applies depolarising noise with probability p on the qubits that the gate touched. This is a simple generic model, not a model of a specific device, and the code is mine, not Qiskit.
| Iterations k | Total gates | CNOT gates | p = 0 | p = 0.001 | p = 0.005 | p = 0.01 | p = 0.02 |
|---|---|---|---|---|---|---|---|
| 1 | 51 | 12 | 0.7812 | 0.7499 | 0.6387 | 0.5271 | 0.3711 |
| 2 | 99 | 24 | 0.9453 | 0.8741 | 0.6467 | 0.4582 | 0.2629 |
| 3 | 147 | 36 | 0.3301 | 0.3088 | 0.2447 | 0.1961 | 0.1511 |
Probability of reading the marked item 101 on three qubits with depolarising noise p after every gate. My own density-matrix simulation. Gate counts include the Toffoli decompositions.
Read across the rows. With perfect gates, two iterations are best. At p = 0.001 two iterations still win, 0.874 against 0.750. At p = 0.005 they are about equal, 0.647 against 0.639. At p = 0.01 one iteration is better, 0.527 against 0.458, and at p = 0.02 it is better again, 0.371 against 0.263. The optimal number of iterations under noise is smaller than the ideal number, and it shrinks as the noise grows. The second iteration doubles the gate count, so it adds more error than the extra amplitude is worth.
The practical rule
On a noisy device the best Grover depth is not the textbook one. Try fewer iterations and measure. A search with a million items needs about 800 iterations ideally, and each contains an oracle and a diffuser, so noisy hardware cannot run it at all without error correction. This is one reason Grover's algorithm is regarded as a fault-tolerant-era algorithm.
The gate counts also show how expensive the Toffoli is. One iteration for eight items uses 12 CNOT gates, all from the two Toffoli gates in the oracle and diffuser. A circuit built from a native three-qubit gate, on hardware that has one, would be shorter, but most superconducting devices need the decomposition. Our lesson on transpilation shows how a compiler chooses it.
When you do not know how many items are marked
The formula above assumes exactly one marked item. With M marked items among N, the angle becomes sin θ = √(M/N), and the best number of iterations is about (π/4)·√(N/M). If M is not known in advance you cannot choose k correctly, and running too many iterations can lower the success probability just as in the example above.
There are two standard ways around this, which I describe from general knowledge and not from a source I opened for this lesson. The first is to estimate M with quantum counting, which uses phase estimation on the Grover iterate and costs about √N queries. The second is to run Grover with randomly chosen iteration counts that grow gradually, checking each result with the oracle, which finds a marked item in order √(N/M) queries without knowing M. Either way the total cost stays on the order of √(N/M).
Worked example
Two marked items among 8
- Now sin θ = √(2/8) = 1/2, so θ = 30 degrees (0.5236 radians).
- After one iteration the probability of landing on a marked item is sin²(3 × 30°) = sin²(90°) = 1.
- The best choice is therefore one iteration, not two.
- Running two iterations gives sin²(150°) = 0.25, a clear drop. The same circuit with the wrong k fails.
This example is the same arithmetic as the four-item case, because two marked items among eight is the same ratio as one among four. The lesson is that the correct iteration count depends on the fraction of marked items, and that is exactly the quantity that is often unknown.
Summary
- The success probability after k iterations is sin²((2k + 1)θ) with sin θ = √(M/N), so it rises and then falls.
- The best number of iterations is about (π/4)·√(N/M). For N = 8 and one marked item it is 2, and a third iteration drops the probability to 0.33.
- Under gate noise the best number of iterations is smaller than the ideal one, as the simulation above shows for three qubits.
- A quadratic speed-up needs very large N to matter in time, which is why it is expected on error-corrected machines.
- Always compare your Qiskit result with the exact simulation or with the widget on this page before blaming the device.
Common mistakes
- Reading the target string in the wrong order. Qubit 0 is the rightmost character. Test with a known target first.
- Forgetting that the oracle only flips a sign. If you measure straight after the oracle without the diffuser, every outcome is still equally likely, because a sign change alone does not change probabilities.
- Running too many iterations. Check the formula and stop near (π/4)√(N/M).
- Marking items without knowing M. The best k depends on it.
- Measuring in the middle of the circuit. Measure only at the end, so that interference can do its work.
- Expecting a clean answer on hardware. Noise grows with circuit depth, and each iteration adds depth.
- Using an old tutorial. Many Grover examples online use functions that the 1.0 and 2.0 releases removed. Check the date and the imports.
The whole program in one place
Here is a compact version that sweeps the iteration count for a three-qubit search and prints the success fraction next to the exact formula. It is useful as a self-check, because the two columns should agree to within shot noise.
import math
from qiskit import QuantumCircuit
from qiskit.primitives import StatevectorSampler
def grover_3q(target, iterations):
bits = target[::-1]
qc = QuantumCircuit(3)
qc.h([0, 1, 2])
for _ in range(iterations):
for i, b in enumerate(bits):
if b == '0': qc.x(i)
qc.ccz(0, 1, 2)
for i, b in enumerate(bits):
if b == '0': qc.x(i)
qc.h([0, 1, 2]); qc.x([0, 1, 2])
qc.ccz(0, 1, 2)
qc.x([0, 1, 2]); qc.h([0, 1, 2])
qc.measure_all()
return qc
theta = math.asin(math.sqrt(1 / 8))
shots = 4096
sampler = StatevectorSampler()
for k in range(5):
counts = sampler.run([(grover_3q('101', k), None, shots)]).result()[0].data.meas.get_counts()
measured = counts.get('101', 0) / shots
exact = math.sin((2 * k + 1) * theta) ** 2
print(k, round(measured, 4), round(exact, 4))The exact column for k = 4 is 0.0122, a long way down from the peak. Plotting the whole curve shows a sine wave: the success chance rises, peaks, and falls to nearly zero before rising again. A search that runs one step past the peak can be worse than one that stops early.
Questions people ask
Does Grover’s algorithm really find the answer in one step?
Only for N = 4 with one marked item, and in the idealised case with no noise. In general the number of steps is about (π/4)√(N/M).
Is Grover’s speed-up exponential?
No. It is quadratic: about √N steps instead of about N. That is a useful saving for large N but much smaller than an exponential one.
Why does the probability go down after the peak?
Each iteration rotates the state by a fixed angle. Once the state has been rotated past the marked direction, further rotation carries it away again.
Do I need a quantum computer to run this?
No. Exact simulators like the one used here run small circuits on an ordinary computer. A real device is needed only to see the effect of noise or to test hardware.
Can I use Qiskit’s built-in Grover tools?
Qiskit has had helper functions for building Grover operators, and I did not check their current names or whether your version still includes them. I built the circuit from basic gates here on purpose, so that every step is visible and does not depend on a helper that may have changed.
Can this search a database?
Only if the database can be turned into an oracle circuit that checks entries, and the data loading cost does not erase the saving. Loading ordinary data into a quantum state is a hard problem of its own, so “quantum search of a database” is mostly a loose phrase.
Practice problems
Check yourself
For N = 16 and one marked item, how many Grover iterations are best? Use (π/4)√N and round.
(π/4) × 4 = 3.14, so 3 iterations. (Computed with the formula: sin θ = 1/4, θ = 0.2527 rad; at k = 3, 7θ = 1.769 rad, sin² = 0.961.)
In the two-qubit circuit with target 01, which qubit needs X gates around the controlled-Z?
Qubit 1. The string 01 has qubit 1 = 0 and qubit 0 = 1, so only the qubit holding a 0 needs the X pair.
What is the success probability for N = 8, M = 1 after three iterations, and why is it lower than after two?
0.3301. The state has rotated past the marked direction (7θ is larger than 90°).
For N = 8 and M = 2, how many iterations are best, and what is the probability?
One iteration, with probability 1.0, because θ = 30° and 3θ = 90°.
If you measure right after the oracle and before the diffuser, what are the probabilities?
Unchanged: a sign flip alone does not change any probability, so every outcome is still equally likely.
Approximately how many iterations for a million items (N ≈ 1,048,576) with one marked?
(π/4) × 1,024 ≈ 804.
Why might a real device give worse results than the simulator for the same circuit?
Gate and measurement errors, which accumulate with circuit depth, and extra gates added when the circuit is transpiled for the device.
References and further reading
I opened IBM’s Sampler guide for the pattern of building a circuit with measure_all(), running a Sampler on a list of circuits, and reading results from the register named meas. The first Qiskit lesson on this site relied on the Qiskit documentation pages on bit ordering and on primitive inputs and outputs. I could not run Qiskit here, so none of the code was executed. Every probability in the lesson comes from my own NumPy simulation of the same gates, using Qiskit’s bit ordering, and the closed-form formula for Grover’s algorithm, which I checked against that simulation. The gate names used (h, x, cz, ccz) are standard Qiskit circuit methods, but I did not check them against the version you have installed.
- Get started with Sampler (IBM Quantum documentation) Opened. Pattern of building a circuit, calling measure_all() to create the register named meas, running a Sampler on a list of circuits and reading results. It uses SamplerV2 from qiskit_ibm_runtime and get_bitstrings(); it does not mention StatevectorSampler or get_counts, which this site’s first Qiskit lesson used from other documentation pages.
- IBM Quantum documentation (IBM) Opened. Overview of Qiskit guides, tutorials and API references.
Key terms in the dictionary