Skip to the content
Kets & Gates homeOpen the app

Lesson 18: Building real oracles

Turning a logic puzzle into a phase oracle, and counting what it costs

about 50 min15 partsbest after lesson 17 and lesson 13

Start the interactive lesson

The interactive version checks every answer, gives hints and saves your progress in this browser. This page is the same lesson on one page, with the answers folded away.

1 / 15 · Learn

Before you start

Lessons 16 and 17 treated the oracle as a box that marks the solutions. This lesson opens the box for a real problem. You turn a logic puzzle into a circuit, check that it marks exactly the right inputs, run Grover search on it in code, and count what the whole search costs. The compute, copy, uncompute pattern of Lesson 13 does much of the work, and the gate costs of Lesson 11 come back at the end.

By the end of this lesson you can:

  • write a logic puzzle as a CNF formula and check an assignment against it;
  • say why an honest oracle checks the clauses instead of listing the answers;
  • build an OR clause from a Toffoli gate, and a phase oracle from compute, phase and uncompute steps;
  • run Grover search on such an oracle in code, choose the number of iterations, and read the solutions from the counts;
  • count the Toffoli and T gates in one oracle call, and compare the whole search with brute force.

Check yourself

A warm-up: make a guess before reading on. The lesson comes back to it.

A formula has 40 variables, so there are 2402^{40} (about 1.1 trillion) possible assignments, and exactly one of them satisfies it. Grover search runs with an oracle that checks the formula. About how many oracle calls does it need?

  1. A1: one call checks every assignment at once
  2. BAbout 40, roughly one per variable
  3. CAbout 820,000
  4. DAbout 550 billion: half the assignments, as when checking them one by one
Show the answer

Answer: C. About 820,000

With N=240N = 2^{40} assignments and one solution, Grover needs about π4N=π4 220≈823,550\tfrac{\pi}{4}\sqrt N = \tfrac{\pi}{4}\,2^{20} \approx 823{,}550 calls. That is far fewer than the 2392^{39} checks brute force needs on average, but it is still exponential in the number of variables: two more variables double it.

Why not the others

  • A. One call does act on every assignment at once, but all it does is put a minus sign on the solution. A measurement right after it gives a random assignment. Turning that sign into a likely outcome takes about π4N\tfrac{\pi}{4}\sqrt N calls.
  • B. That would make SAT easy, and no quantum algorithm is known to do that. Grover’s count grows with the square root of the number of assignments, 240=220\sqrt{2^{40}} = 2^{20}, not with the number of variables.
  • D. That is the classical average, 2392^{39} checks. Grover gives a real gain: about π4240\tfrac{\pi}{4}\sqrt{2^{40}} calls, the square root of the classical count.

Check yourself

A warm-up: make a guess before reading on. The lesson comes back to it.

You want Grover search to solve a logic puzzle. What do you need in order to build its oracle?

  1. AA circuit that checks the rules on any proposed solution
  2. BOnly the number of solutions
  3. CThe list of solutions, so that the oracle knows which inputs to mark
  4. DA quantum memory loaded with every candidate in advance
Show the answer

Answer: A. A circuit that checks the rules on any proposed solution

A search oracle is a circuit that checks the rules on whatever input it gets and flips the sign when they all hold. Building it takes the rules, not the answers.

Why not the others

  • B. The number of solutions helps you choose how many Grover iterations to run, but it can’t mark anything. Marking is done by a circuit that checks the rules on its input.
  • C. With the list in hand there would be nothing left to search for. The oracle only has to recognise a solution when it sees one: a circuit that checks the rules on its input marks exactly the solutions, and nobody needs to know in advance which they are.
  • D. Loading every candidate would take as many steps as checking them all classically. The superposition of all candidates comes from Hadamards on the input qubits; the oracle then computes the rules on it.

2 / 15 · Learn

Logic puzzles as formulas

Three friends, Ana, Ben and Cy, are deciding whether to come to a party. Write x0=1x_0 = 1 if Ana comes and x0=0x_0 = 0 if not, and likewise x1x_1 for Ben and x2x_2 for Cy. They agree on two rules:

  • if Ben comes, Ana comes. This fails only when Ben comes without Ana, so it reads x0∨¬x1x_0 \lor \lnot x_1;
  • Ben or Cy comes, or both: x1∨x2x_1 \lor x_2.

Each rule is a clause: an OR of literals, where a literal is a variable (x1x_1) or its negation (¬x1\lnot x_1). The puzzle wants all its clauses at once, so it is their AND:

φ=(x0∨¬x1)∧(x1∨x2)\varphi = (x_0 \lor \lnot x_1) \land (x_1 \lor x_2)

An AND of clauses is a formula in conjunctive normal form (CNF). An assignment gives every variable a value; write it as a bit string x0x1x2x_0x_1x_2. It satisfies φ\varphi when every clause holds, and then φ(x)=1\varphi(x) = 1.

Check yourself

Ben and Cy come, Ana doesn’t: x0x1x2=011x_0x_1x_2 = 011. Does this assignment satisfy φ=(x0∨¬x1)∧(x1∨x2)\varphi = (x_0 \lor \lnot x_1) \land (x_1 \lor x_2)?

  1. ANo: the second clause fails
  2. BYes: two of the three variables are 1
  3. CYes: the second clause holds
  4. DNo: the first clause fails
Show the answer

Answer: D. No: the first clause fails

Clause 1: x0∨¬x1=0∨0=0x_0 \lor \lnot x_1 = 0 \lor 0 = 0, so φ(011)=0\varphi(011) = 0 whatever clause 2 says. Ben came without Ana.

Why not the others

  • A. The second clause holds: x1=1x_1 = 1, so x1∨x2=1x_1 \lor x_2 = 1. It is the first that fails: x0=0x_0 = 0 and ¬x1=0\lnot x_1 = 0.
  • B. Counting 1s says nothing about the rules. Check each clause: the first, x0∨¬x1x_0 \lor \lnot x_1, is 0∨0=00 \lor 0 = 0, so the formula is 0.
  • C. A CNF formula needs every clause to hold, not just one. Here x1∨x2=1x_1 \lor x_2 = 1, but x0∨¬x1=0∨0=0x_0 \lor \lnot x_1 = 0 \lor 0 = 0: Ben comes without Ana.

Checking one assignment is quick: evaluate each clause and take the AND, a few steps per clause. Finding a satisfying assignment is the hard direction. With nn variables there are 2n2^n assignments, and brute force tries them one by one: up to 2n2^n checks. Practical solvers prune cleverly and handle many large formulas, but no known method avoids exponential time in the worst case.

The satisfiability problem, SAT, is NP-complete. NP is the class of problems whose solutions can be checked quickly, and a fast algorithm for SAT would give a fast algorithm for every one of them, from timetabling to packing boxes. Most researchers believe that no such algorithm exists. The table below checks all eight assignments of the party formula.

The party formula on all eight assignments. Shaded rows satisfy both clauses. The last column is the sign (−1)φ(x)(-1)^{\varphi(x)} that a phase oracle will put on ∣x⟩\ket x, drawn as a needle as in circle notation: right for +1+1, left for −1-1.

Check yourself

How many of the eight assignments x0x1x2x_0x_1x_2 satisfy (x0∨x2)∧(¬x0∨¬x1)∧(x1∨¬x2)(x_0 \lor x_2) \land (\lnot x_0 \lor \lnot x_1) \land (x_1 \lor \lnot x_2)?

Hints
  1. Which assignments make each clause false?
  2. A clause of two literals is false only when both literals are false: that fixes two variables and leaves the third free, so it rules out two assignments. Strike them out for each clause and count what is left.
Show the answer

Answer: 22

The satisfying assignments are 011 and 100: 2 of the eight.

Each clause rules out the assignments where all its literals are false. Clause 1, x0∨x2x_0 \lor x_2, rules out 000 and 010. Clause 2, ¬x0∨¬x1\lnot x_0 \lor \lnot x_1, rules out 110 and 111. Clause 3, x1∨¬x2x_1 \lor \lnot x_2, rules out 001 and 101. What is left: 011 and 100, so 2 assignments.

Common slips

  • 66: That counts the assignments that fail. 6 of the eight make some clause false, so 2 satisfy every clause.
  • 88: That counts the assignments where at least one clause holds. A CNF formula is an AND: every clause has to hold.
  • 44: That leaves out the last clause. Check it on the assignments that pass the others.

3 / 15 · Learn

An honest oracle

Grover search needs a phase oracle (Lesson 16): O∣x⟩=(−1)φ(x)∣x⟩O\ket x = (-1)^{\varphi(x)}\ket x, a minus sign on exactly the satisfying assignments. For the party, those are the four shaded rows of the table.

One way to build OO is to read it off the table: one multi-controlled Z for each solution, firing on that bit string alone. But writing that circuit takes the list of solutions, and with the list in hand there is nothing left to search for. Such an oracle presupposes the answer.

An honest oracle is built from the formula alone. It evaluates the clauses on whatever assignment it is given, as a classical checker would, and flips the sign when they all hold. Its size grows with the number of clauses, not with 2n2^n, and nobody needs to know in advance which inputs it will mark. Finding them is the search’s job.

Check yourself

Two students build a phase oracle for a 50-variable formula. Alice writes a gadget for each clause, then an AND and an uncompute. Bob lets a classical computer run until it has found every satisfying assignment, then writes one multi-controlled Z for each. Both circuits put the same signs on the same inputs. Whose construction is useful for search?

  1. ABob’s: it marks the solutions directly, so it is sure to be right
  2. BAlice’s
  3. CNeither: any oracle that marks the solutions must already contain them
  4. DBoth: they are the same operation, so they are equally useful
Hint
  1. What did each student need to know before writing the circuit?
Show the answer

Answer: B. Alice’s

Alice’s oracle is built from the formula alone, at a size that grows with the number of clauses. Bob’s needs the solutions first, and finding them is the search itself.

Why not the others

  • A. It is right, but by the time Bob can write it the search is over: finding every solution took up to 2502^{50} checks. An oracle that needs the answers before it can be built saves nothing.
  • C. Alice’s oracle contains the rules, not the solutions. It computes each clause on its input, the quick checking direction, and the signs follow; nobody knows in advance which inputs will get them.
  • D. They are the same operation, but not the same cost. Alice builds hers from the formula in a number of steps that grows with the number of clauses; Bob needs the answers first, which is the whole search.

4 / 15 · Learn

One clause from a Toffoli

Start with one clause, x0∨x1x_0 \lor x_1. A Toffoli computes an AND, not an OR, so use De Morgan’s law:

a∨b=¬(¬a∧¬b)a \lor b = \lnot(\lnot a \land \lnot b)

An OR is false only when every literal is false. So:

  1. Flip a work qubit ww, which starts at ∣0⟩\ket0, when x0=0x_0 = 0 and x1=0x_1 = 0. A Toffoli with two anti-controls does this: an anti-control, drawn ○, fires when its qubit is 0 instead of 1. (With ordinary controls only, put an X on each input before and after the Toffoli.)
  2. Flip ww with an X. Now w=1w = 1 unless both literals are false: w=x0∨x1w = x_0 \lor x_1.

A negated literal such as ¬x1\lnot x_1 is false when x1=1x_1 = 1, so it gets an ordinary control instead. The inputs pass through unchanged, so the gadget is reversible.

Check yourself

Build the clause x0∨¬x1x_0 \lor \lnot x_1: for every input ∣x0x1⟩∣0⟩\ket{x_0x_1}\ket0, the work qubit ww (bottom wire) should end as x0∨¬x1x_0 \lor \lnot x_1, and the inputs should be unchanged.

Build it in the circuit builder (gates: X, control, anti-control).

Hints
  1. On which single input is x0∨¬x1x_0 \lor \lnot x_1 false?
  2. It is false only for x0=0x_0 = 0, x1=1x_1 = 1. Fire a Toffoli there: an anti-control on x0x_0, an ordinary control on x1x_1, target ww.
  3. Then flip ww with an X.
Show the answer

One circuit that works: controlled-X q1,q0=0→q2, then X on q2.

The clause is false only for x0=0x_0 = 0, x1=1x_1 = 1. A Toffoli with an anti-control on x0x_0 and a control on x1x_1 flips ww there, and the X on ww turns that into 1 everywhere else: w=x0∨¬x1w = x_0 \lor \lnot x_1.

Clauses with three literals, and why they matter

A clause with three literals, such as x0∨¬x1∨x2x_0 \lor \lnot x_1 \lor x_2, works the same way with one more control: a 3-controlled X fires on the one setting of its three variables that makes the clause false, then an X flips ww.

This matters for honesty about hardness. Formulas whose clauses all have two literals (2-SAT) can be solved quickly by a clever classical algorithm. With three literals per clause the problem, 3-SAT, is NP-complete. This lesson’s examples use two literals only to keep the circuits small; the construction is the same.

5 / 15 · Learn

From clauses to a phase oracle

Give each of the mm clauses its own work qubit, holding c1(x),…,cm(x)c_1(x), \ldots, c_m(x). The formula is the AND of those qubits, and a multi-controlled gate computes an AND. Aim an mm⁠-controlled X at an output qubit prepared in ∣−⟩\ket-. It flips the output exactly when every clause holds, and flipping ∣−⟩\ket- gives −∣−⟩-\ket-. That is phase kickback (Lesson 9): the output stays ∣−⟩\ket-, and the branch ∣x⟩\ket x picks up the sign (−1)φ(x)(-1)^{\varphi(x)}. (A multi-controlled Z across the clause qubits does the same job without the output qubit.)

One step is left. The work qubits now hold the clause values c(x)c(x), a record that differs from branch to branch. Lesson 13 showed what such leftovers do: they stop the branches from interfering. So run the clause gadgets again in reverse order, which returns every work qubit to ∣0⟩\ket0. The whole oracle is compute, phase, uncompute.

The honest phase oracle. CC computes the clause values into the work qubits; the AND flips the output, whose ∣−⟩\ket- turns the flip into the sign (−1)φ(x)(-1)^{\varphi(x)}; C−1C^{-1} clears the work qubits. Read the four states below the circuit: only at step 4 is the sign all that is left.

Check yourself

Grover search measures only the variable qubits, never the work qubits. Why must the oracle still uncompute the clause values?

  1. AIt shouldn’t: running the clause gadgets backwards would also undo the minus signs
  2. BThe clause values differ from branch to branch; left in place, they stop the branches from interfering
  3. COnly so that the next oracle call can reuse the work qubits
  4. DIt needn’t: qubits that are never measured can’t affect the result
Show the answer

Answer: B. The clause values differ from branch to branch; left in place, they stop the branches from interfering

After the AND, each branch is (−1)φ(x)∣x⟩∣c(x)⟩(-1)^{\varphi(x)}\ket x\ket{c(x)}. The records c(x)c(x) differ between branches, so the variables are entangled with the work qubits and the diffusion step can’t make the branches interfere. Uncomputing returns the work qubits to ∣0…0⟩\ket{0\ldots0} on every branch and leaves only the sign.

Why not the others

  • A. The signs come from the AND step, which the uncompute doesn’t repeat. The clause gadgets act on each branch the same way whatever its sign, so they clear the work qubits and leave the signs alone.
  • C. Reuse is a bonus, not the reason. Even with fresh work qubits for every call, the leftover records would tell the branches apart and block the interference Grover depends on.
  • D. Unmeasured qubits still matter when they are entangled with the ones you measure. Left in place, each branch ∣x⟩\ket x carries its own record ∣c(x)⟩\ket{c(x)}, and branches with different records can’t interfere. Lesson 13 showed the same effect.

6 / 15 · Worked example

Worked example: the party oracle on four qubits

The party formula φ=(x0∨¬x1)∧(x1∨x2)\varphi = (x_0 \lor \lnot x_1) \land (x_1 \lor x_2) on four qubits: the variables x0,x1,x2x_0, x_1, x_2 and one work qubit ww. Clause 1 goes into ww. Clause 2 is folded into the phase step, so it needs no work qubit of its own.

Worked example

Building OO for the party formula

  1. Compute clause 1

    Clause 1, x0∨¬x1x_0 \lor \lnot x_1, is false only when x0=0x_0 = 0 and x1=1x_1 = 1. So the Toffoli gets an anti-control on x0x_0 and an ordinary control on x1x_1, and an X on ww follows. Check the input ∣010⟩∣0⟩\ket{010}\ket0, Ben without Ana: the Toffoli fires, ww becomes 1, and the X makes it 0. Clause 1 fails, and ww says so.

  2. Phase

    The sign belongs on the branches where w=1w = 1 and clause 2, x1∨x2x_1 \lor x_2, holds. Use De Morgan on the sign. A Z on ww puts −1-1 on every branch with w=1w = 1. A second Z on ww, with anti-controls on x1x_1 and x2x_2, multiplies by −1-1 again where x1=x2=0x_1 = x_2 = 0, the one case in which clause 2 fails. In one line, with xˉ\bar x for NOT xx:

    (−1)w (x1∨x2)=(−1)w (−1)w xˉ1xˉ2(-1)^{w\,(x_1 \lor x_2)} = (-1)^{w}\,(-1)^{w\,\bar x_1 \bar x_2}
  3. Uncompute

    Repeat the clause-1 gates in reverse order: the X on ww, then the same Toffoli. They return ww to 0 on every branch, and neither touches the sign. So ∣x⟩∣0⟩→(−1)φ(x)∣x⟩∣0⟩\ket x\ket0 \to (-1)^{\varphi(x)}\ket x\ket0: a phase oracle on three variables with one work qubit.

  4. Your turn: the signs

    Use the clauses rather than the simulator.

    Your turn

    Which inputs ∣x0x1x2⟩∣0⟩\ket{x_0x_1x_2}\ket0 come out of the party oracle with a minus sign? Select all.

    Select all that apply.

    1. A∣000⟩\ket{000}
    2. B∣001⟩\ket{001}
    3. C∣010⟩\ket{010}
    4. D∣011⟩\ket{011}
    5. E∣100⟩\ket{100}
    6. F∣101⟩\ket{101}
    7. G∣110⟩\ket{110}
    8. H∣111⟩\ket{111}
    Hints
    1. Only the satisfying assignments get a sign. Test each clause.
    2. A two-literal clause is false only when both of its literals are false.
    Show the answer

    Answers: B. ∣001⟩\ket{001}; F. ∣101⟩\ket{101}; G. ∣110⟩\ket{110}; H. ∣111⟩\ket{111}

    The sign is −1-1 exactly where every clause holds: on ∣001⟩\ket{001}, ∣101⟩\ket{101}, ∣110⟩\ket{110} and ∣111⟩\ket{111}.

    Why not the others

    • A. Clause 2, x1∨x2x_1 \lor x_2, is false here: x1=0x_1 = 0 and x2=0x_2 = 0. No minus sign.
    • C. Clause 1, x0∨¬x1x_0 \lor \lnot x_1, is false here: x0=0x_0 = 0 and x1=1x_1 = 1. No minus sign.
    • D. Clause 1, x0∨¬x1x_0 \lor \lnot x_1, is false here: x0=0x_0 = 0 and x1=1x_1 = 1. No minus sign.
    • E. Clause 2, x1∨x2x_1 \lor x_2, is false here: x1=0x_1 = 0 and x2=0x_2 = 0. No minus sign.
  5. Your turn: a new rule

    Cy changes rule 2 to “Ben comes, or Cy stays home”: x1∨¬x2x_1 \lor \lnot x_2. Clause 1 is unchanged, so the compute and uncompute columns stay as they are.

    Your turn

    Fill in the phase step, columns 3 and 4, so that the circuit is the phase oracle for (x0∨¬x1)∧(x1∨¬x2)(x_0 \lor \lnot x_1) \land (x_1 \lor \lnot x_2).

    Build it in the circuit builder (gates: Z, control, anti-control, X).

    Hints
    1. On which setting of x1x_1 and x2x_2 is the new clause 2 false?
    2. It fails only for x1=0x_1 = 0, x2=1x_2 = 1. Keep the Z on ww; the second Z on ww needs an anti-control on x1x_1 and an ordinary control on x2x_2.
    Show the answer

    One circuit that works: controlled-X q1,q0=0→q3, then X on q3, then Z on q3, then controlled-Z q2,q1=0→q3, then X on q3, then controlled-X q1,q0=0→q3.

    A Z on ww marks every branch with w=1w = 1. The second Z on ww, with an anti-control on x1x_1 and a control on x2x_2, removes the mark where x1=0x_1 = 0 and x2=1x_2 = 1, the one case in which x1∨¬x2x_1 \lor \lnot x_2 fails. The signs land on 000000, 100100, 110110 and 111111.

One more, fully worked: ψ=(¬x0∨x2)∧(x0∨x1)\psi = (\lnot x_0 \lor x_2) \land (x_0 \lor x_1), with the same four qubits.

Another worked example

Another example: (¬x0∨x2)∧(x0∨x1)(\lnot x_0 \lor x_2) \land (x_0 \lor x_1)

  1. Compute clause 1

    ¬x0∨x2\lnot x_0 \lor x_2 is false only when x0=1x_0 = 1 and x2=0x_2 = 0: a Toffoli with an ordinary control on x0x_0 and an anti-control on x2x_2, then an X on ww. Now w=c1(x)w = c_1(x).

  2. Phase

    Clause 2, x0∨x1x_0 \lor x_1, fails only when x0=x1=0x_0 = x_1 = 0: a Z on ww, then a Z on ww with anti-controls on x0x_0 and x1x_1. The sign is −1-1 exactly where w=1w = 1 and clause 2 holds.

  3. Uncompute

    The X on ww, then the same Toffoli, return ww to 0 on every branch.

  4. Signs

    If x0=1x_0 = 1, clause 1 needs x2=1x_2 = 1: that gives 101101 and 111111. If x0=0x_0 = 0, clause 2 needs x1=1x_1 = 1: that gives 010010 and 011011. Those four inputs pick up −1-1; the other four keep +1+1.

7 / 15 · Learn

The oracle in code

In code, write each clause as a list of literals. A literal is a pair (q, v): it holds when qubit qq has the value vv. So (1, 0) is ¬x1\lnot x_1 and (2, 1) is x2x_2.

The function clause below is the De Morgan gadget, written with X gates around ordinary controls instead of anti-controls. It flips each qubit whose literal needs a 1, so that the qubit reads 1 exactly when its literal is false; fires an mcx onto the work qubit; flips the qubits back; and ends with an X on the work qubit. The same function handles clauses of any length.

This program is the bit-flip form of the party oracle, ∣x⟩∣00⟩∣y⟩→∣x⟩∣00⟩∣y⊕φ(x)⟩\ket x\ket{00}\ket y \to \ket x\ket{00}\ket{y\oplus\varphi(x)}. With the output in ∣−⟩\ket- instead of ∣y⟩\ket y, the flip becomes the sign. But the program is missing a step.

Check yourself

The program computes both clauses into work qubits 3 and 4, then ANDs them into the output, qubit 5. It forgets to clean up. Add the uncompute step, so that every input ∣x0x1x2⟩∣00⟩∣0⟩\ket{x_0x_1x_2}\ket{00}\ket0 ends as ∣x0x1x2⟩∣00⟩∣φ(x)⟩\ket{x_0x_1x_2}\ket{00}\ket{\varphi(x)}. The checker tries all eight inputs.

from qiskit import QuantumCircuit

n = 3                          # variables x0, x1, x2: qubits 0-2
clauses = [[(0, 1), (1, 0)],   # x0 or (not x1)
           [(1, 1), (2, 1)]]   # x1 or x2
m = len(clauses)               # work qubits 3-4, one per clause
out = n + m                    # output qubit 5

def clause(qc, lits, w):
    """Put the OR of the literals into work qubit w, which starts at 0."""
    for q, v in lits:
        if v == 1:
            qc.x(q)            # now q reads 1 exactly when its literal is false
    qc.mcx([q for q, v in lits], w)    # w = 1 when every literal is false
    for q, v in lits:
        if v == 1:
            qc.x(q)            # undo the flips
    qc.x(w)                    # De Morgan: OR = NOT (all false)

qc = QuantumCircuit(n + m + 1)
for k in range(m):
    clause(qc, clauses[k], n + k)        # compute the clauses
qc.mcx(list(range(n, n + m)), out)       # AND of the clauses into the output
# uncompute the clause qubits here

Write the program in the app’s code editor (Python with Qiskit’s circuit methods), run it, and check it.

Hints
  1. Run it first: from ∣000000⟩\ket{000000} the state ends as ∣000100⟩\ket{000100}, because clause 1 holds and its work qubit still says so.
  2. Each clause gadget undoes itself: running it a second time returns its work qubit to 0.
  3. Repeat the compute loop after the mcx line.
Show the answer

One program that works:

from qiskit import QuantumCircuit

n = 3                          # variables x0, x1, x2: qubits 0-2
clauses = [[(0, 1), (1, 0)],   # x0 or (not x1)
           [(1, 1), (2, 1)]]   # x1 or x2
m = len(clauses)               # work qubits 3-4, one per clause
out = n + m                    # output qubit 5

def clause(qc, lits, w):
    """Put the OR of the literals into work qubit w, which starts at 0."""
    for q, v in lits:
        if v == 1:
            qc.x(q)            # now q reads 1 exactly when its literal is false
    qc.mcx([q for q, v in lits], w)    # w = 1 when every literal is false
    for q, v in lits:
        if v == 1:
            qc.x(q)            # undo the flips
    qc.x(w)                    # De Morgan: OR = NOT (all false)

qc = QuantumCircuit(n + m + 1)
for k in range(m):
    clause(qc, clauses[k], n + k)        # compute the clauses
qc.mcx(list(range(n, n + m)), out)       # AND of the clauses into the output
for k in range(m):
    clause(qc, clauses[k], n + k)        # uncompute: each gadget undoes itself

Each clause gadget is its own inverse, and the gadgets act on different work qubits, so running the loop again clears qubits 3 and 4 on every input. The output keeps φ(x)\varphi(x), because the uncompute never touches qubit 5.

8 / 15 · Learn

Grover search on the puzzle

Now a bigger party. Dee joins (x3x_3), and there are four rules:

  • Ana or Ben comes: x0∨x1x_0 \lor x_1;
  • if Ana comes, Cy comes: ¬x0∨x2\lnot x_0 \lor x_2;
  • Ben and Dee don’t both come: ¬x1∨¬x3\lnot x_1 \lor \lnot x_3;
  • if Cy comes, Dee comes: ¬x2∨x3\lnot x_2 \lor x_3.

The program below builds the honest oracle with one work qubit per clause (qubits 4 to 7) and an output qubit (8) in ∣−⟩\ket-, then runs Grover search with the diffusion step of Lesson 16 (the function diffuser below). How many iterations? With NN assignments, of which MM are solutions, about π4N/M\tfrac{\pi}{4}\sqrt{N/M}, rounded to a whole number. Here a quick classical count gives M=2M = 2 of N=16N = 16, and π48≈2.22\tfrac{\pi}{4}\sqrt8 \approx 2.22: two iterations. (In a real search you wouldn’t know MM; Lesson 17 showed how to manage without it.)

Check yourself

Grover search on four variables x0,…,x3x_0, \ldots, x_3 (qubits 0 to 3) ends with qc.measure(range(4), range(4)). The counts begin {'0010': 474, '1101': 468, '0111': 6, '1000': 5, …}. Which assignments, written x0x1x2x3x_0x_1x_2x_3, did it find?

  1. AOnly 0100: the most frequent string, read backwards
  2. B0100 and 1011
  3. CEvery string that appears in the counts
  4. D0010 and 1101, as printed
Show the answer

Answer: B. 0100 and 1011

Qiskit puts x0x_0 on the right, so read the strings backwards: '0010' is 0100 and '1101' is 1011. Two counts of nearly equal size mean two solutions, and checking each against the formula takes a moment.

Why not the others

  • A. The two big counts differ by a few shots in a thousand, which is sampling noise: both strings came up nearly half the time, so 1011 is a solution too.
  • C. Grover leaves a small chance of a wrong answer, and those few shots land on the other strings. Each candidate is quick to check against the formula; the two big counts are the solutions.
  • D. Qiskit prints classical bit 0, which holds qubit 0 and so x0x_0, as the rightmost character. Read each string backwards: '0010' is x0x1x2x3=0100x_0x_1x_2x_3 = 0100.

Check yourself

Grover search over the 242^{4} assignments of a 4-variable formula with exactly one satisfying assignment. How many iterations should it run?

Hints
  1. How does the best number of iterations depend on NN and MM?
  2. About π4N/M\tfrac{\pi}{4}\sqrt{N/M}, rounded to a whole number.
Show the answer

Answer: 33

π424/1=π416≈3.14\tfrac{\pi}{4}\sqrt{2^{4}/1} = \tfrac{\pi}{4}\sqrt{16} \approx 3.14, so 3 iterations.

Common slips

  • 44: That leaves out the factor π4\tfrac{\pi}{4}. Each iteration turns the state by a fixed angle, and about π4N/M\tfrac{\pi}{4}\sqrt{N/M} turns reach the solutions.
  • 88: That is about how many checks a classical search needs on average. Grover needs about the square root of that: π4N/M\tfrac{\pi}{4}\sqrt{N/M}.

9 / 15 · Explore

Skip the uncompute?

Predict, then see

The program below is the four-friend search with one change: UNCOMPUTE = False, so every oracle call computes the clauses and leaves them in the work qubits. It also runs a single iteration, to keep the comparison simple. With the uncompute switched on, that one iteration finds a solution 78% of the time. Without it, how often does a run give one of the two solutions?

  1. AMore than 78%: fewer gates leave fewer chances for error
  2. B0%: the solutions never come up
  3. CAbout 78%, as before: the work qubits are never measured, so they can’t matter
  4. DAbout 14%, hardly better than the 2 in 16 (12.5%) of a blind guess

Why did skipping the uncompute spoil the search, even though the work qubits are never measured? A sentence or two is enough.

Show what happens

What happens: D. About 14%, hardly better than the 2 in 16 (12.5%) of a blind guess

Without the uncompute, each branch ∣x⟩\ket x carries its own record ∣c(x)⟩\ket{c(x)} in the work qubits. The diffusion step acts on the variable qubits only, and two branches can interfere only if everything else about them is the same. Branches with different records don’t, so the reflection that should pile amplitude onto the solutions has little to work with: the solutions come up 37256≈14%\tfrac{37}{256} \approx 14\% of the time, close to a blind guess. With the uncompute, every branch ends with ∣0000⟩\ket{0000} in the work qubits, and the interference works: 2532≈78%\tfrac{25}{32} \approx 78\% after one iteration, and about 95% after two.

Why not the others

  • A. This simulator makes no errors, so fewer gates can’t help; the circuit is simply a different one. Without the uncompute, the two solutions came up only about 14% of the time.
  • B. Nothing cancels the solutions completely. Without working interference they come up about as often as any other strings: about 14% of runs for the two together.
  • C. That is the tempting view: what you don’t measure can’t hurt. The run shows otherwise: the two solutions together came up only about 14% of the time. The leftover clause values are entangled with the variables, and that blocks the interference.

10 / 15 · Learn

What one oracle call costs

Count Toffoli gates: on an error-corrected machine each one takes 7 T gates (Lesson 11), and T gates are the expensive part there. X gates are cheap, so leave them out. For a formula with mm clauses of two literals each:

  • computing the clauses takes mm Toffolis, one per clause;
  • the AND of the mm clause qubits is an mm⁠-controlled X, which can be built from 2m−32m - 3 Toffolis and m−2m - 2 extra work qubits (below);
  • uncomputing the clauses takes mm Toffolis again.

That makes 4m−34m - 3 Toffolis per call, and 7(4m−3)7(4m - 3) T gates. The four-friend oracle, with m=4m = 4, uses 13 Toffolis and 91 T gates per call. The simulator runs mcx as one gate; real hardware can’t.

A 4-controlled X from Toffolis. The first two compute c1c2c_1c_2, then c1c2c3c_1c_2c_3, into work qubits; the middle one writes c1c2c3c4c_1c_2c_3c_4 onto the target; the last two uncompute, so the work qubits end at ∣0⟩\ket0. Compute, copy, uncompute once more. With mm controls it takes 2m−32m - 3 Toffolis.

Check yourself

An honest oracle for a formula with 10 clauses of 2 literals each computes every clause into its own work qubit, ANDs the 10 clause qubits into the output, and uncomputes the clauses. Build each jj⁠-controlled X from 2j−32j - 3 Toffolis. How many Toffolis does one oracle call use?

Hints
  1. Count three parts: compute the clauses, the AND, uncompute the clauses.
  2. A 2-literal clause is a 2-controlled X: 2⋅2−3=12\cdot2 - 3 = 1 Toffoli. The AND is a 10-controlled X: 2⋅10−3=172\cdot10 - 3 = 17.
Show the answer

Answer: 3737

Clauses: 10×1=1010 \times 1 = 10 Toffolis to compute and as many to uncompute. The AND: 1717. Total 20+17=3720 + 17 = 37 Toffolis per call.

Common slips

  • 2727: That leaves out the uncompute. The clause gadgets run a second time, in reverse, to clear the work qubits, and that costs as many Toffolis again.
  • 2121: The AND of 10 clause qubits is a 10-controlled X, which takes 2⋅10−3=172\cdot10 - 3 = 17 Toffolis, not one.
  • 1717: That counts only the AND. Every clause gadget is a multi-controlled X too, run once to compute and once to uncompute.

Now multiply by the number of calls. With one solution among N=2nN = 2^n assignments, Grover needs about π42n=π4 2n/2\tfrac{\pi}{4}\sqrt{2^n} = \tfrac{\pi}{4}\,2^{n/2} calls, against up to 2n2^n checks for brute force. Grover halves the exponent, from nn to n/2n/2, but doesn’t remove it: two more variables still double the work. And as Lesson 10 noted, no quantum algorithm can search an unstructured space with far fewer than N\sqrt N calls.

So the honest summary is a quadratic speed-up over brute force, not an efficient algorithm. No quantum algorithm is known to solve SAT, or any NP-complete problem, in polynomial time, and most researchers believe none exists. Grover-style search can also speed up cleverer classical methods, such as backtracking solvers, by a square root of their own cost, but that doesn’t make the problems easy either.

Check yourself

A headline reads: “Quantum computers will crack SAT and other NP-complete problems in a flash.” Which verdict is accurate?

  1. AAccurate: one oracle call tests all 2n2^n assignments at once
  2. BAccurate: the oracle checks a formula quickly, so the whole search is quick
  3. CExaggerated: Grover gives a square-root speed-up over brute force, which is still exponential
  4. DWrong the other way: quantum computers give no speed-up at all on SAT
Show the answer

Answer: C. Exaggerated: Grover gives a square-root speed-up over brute force, which is still exponential

Grover needs about π42n\tfrac{\pi}{4}\sqrt{2^n} oracle calls where brute force needs up to 2n2^n checks: a square root, but still exponential in nn. No quantum algorithm is known to solve NP-complete problems in polynomial time, and most researchers believe none exists.

Why not the others

  • A. One call marks every solution with a sign, but a measurement then returns one random assignment. Turning the signs into a likely solution takes about π42n\tfrac{\pi}{4}\sqrt{2^n} calls.
  • B. Each check is quick, but the search still needs about π42n\tfrac{\pi}{4}\sqrt{2^n} calls, which doubles with every two extra variables. No quantum algorithm is known to solve NP-complete problems in polynomial time.
  • D. Grover does give a real speed-up: about 2n/22^{n/2} calls instead of up to 2n2^n checks. It is quadratic, not exponential, and it pays off only for large nn, but it exists.

11 / 15 · Worked example

Worked example: when does the square root pay off?

Worked example

Brute force against Grover, in seconds

The speeds below are made up, chosen so the arithmetic is exact. They are not measurements or forecasts of any real machine.

  1. Assumptions

    A classical computer checks 2302^{30} assignments a second, about 1.07 billion. A quantum computer runs 210=10242^{10} = 1024 Grover iterations a second: each iteration is an oracle call with its many T gates, plus the diffusion step, on a slow error-corrected machine. The formula has nn variables and one solution. Count 2n2^n checks for brute force (its worst case) and 2n/22^{n/2} iterations for Grover (leaving out the constant factor π4\tfrac{\pi}{4}).

  2. Times

    Classical: 2n/230=2n−302^n / 2^{30} = 2^{n-30} seconds. Quantum: 2n/2/210=2n/2−102^{n/2} / 2^{10} = 2^{n/2-10} seconds. At n=30n = 30 the classical computer needs 20=12^0 = 1 second and the quantum one 25=322^{5} = 32 seconds. For small nn the slow quantum steps lose.

  3. Break-even

    The times are equal when the exponents are: n−30=n/2−10n - 30 = n/2 - 10, so n/2=20n/2 = 20 and n=40n = 40. Both then take 210=10242^{10} = 1024 seconds, about 17 minutes. Past that point the quantum computer pulls ahead: two more variables multiply its time by 2 and the classical time by 4.

  4. Your turn: n = 60

    Your turn

    With the same speeds, how many seconds does the quantum computer take at n=60n = 60? A power of 2 is fine.

    Hints
    1. How many iterations does Grover need at n=60n = 60?
    2. 260/2=2302^{60/2} = 2^{30} iterations at 2102^{10} a second.
    Show the answer

    Answer: 10485761048576

    260/2=2302^{60/2} = 2^{30} iterations at 2102^{10} a second take 220=1,048,5762^{20} = 1{,}048{,}576 seconds, about 12 days.

    Common slips

    • 10737418241073741824: 2302^{30} is the number of Grover iterations (and also the classical time in seconds). Divide the iterations by the speed of 2102^{10} a second.
    • 11258999068426241125899906842624: That uses 2n−102^{n-10}. Grover needs 2n/22^{n/2} iterations, not 2n2^n: the time is 230/2102^{30}/2^{10} seconds.
    • 10995116277761099511627776: That multiplies by the speed. Iterations divided by iterations per second gives seconds: 230/2102^{30}/2^{10}.
  5. Your turn: the ratio

    Your turn

    At n=60n = 60, how many times longer than the quantum computer does the classical one take?

    Hints
    1. Write both times at n=60n = 60 as powers of 2.
    2. Classical 2302^{30} seconds, quantum 2202^{20} seconds.
    Show the answer

    Answer: 10241024

    Classical 260−30=2302^{60-30} = 2^{30} seconds (about 34 years), quantum 2202^{20} seconds (about 12 days): a factor of 210=10242^{10} = 1024.

    Common slips

    • 1010: That is the difference of the exponents, 30−2030 - 20. The ratio of the times is 2 to that power: 230/220=2102^{30}/2^{20} = 2^{10}.
    • 10737418241073741824: That is the classical time in seconds. Divide it by the quantum time, 2202^{20} seconds.
    • 10485761048576: That is the quantum time in seconds. The ratio is 230/2202^{30}/2^{20}.

One more, fully worked, with other made-up speeds.

Another worked example

Another example: different speeds

  1. Assumptions

    Classical: 2332^{33} checks a second, eight of the machines above. Quantum: 2142^{14} iterations a second, sixteen times faster than before. Still 2n2^n checks against 2n/22^{n/2} iterations.

  2. Times

    Classical 2n−332^{n-33} seconds; quantum 2n/2−142^{n/2-14} seconds.

  3. Break-even

    n−33=n/2−14n - 33 = n/2 - 14 gives n/2=19n/2 = 19, so n=38n = 38. Both take 238−33=25=322^{38-33} = 2^5 = 32 seconds.

  4. At n = 60

    Quantum: 230−14=2162^{30-14} = 2^{16} seconds, about 18 hours. Classical: 260−33=2272^{60-33} = 2^{27} seconds, about 4.3 years. The ratio is 227−16=211=20482^{27-16} = 2^{11} = 2048.

The two running times under the first set of made-up speeds, on a log scale. Brute force (amber) climbs twice as steeply as Grover (blue). They cross at n=40n = 40; at n=60n = 60 brute force needs about 34 years and Grover about 12 days. But Grover’s line still climbs: at n=100n = 100 it would need 2402^{40} seconds, about 35,000 years.

Check yourself

Made-up speeds: a classical computer checks 2302^{30} assignments a second, and a quantum computer runs 2122^{12} Grover iterations a second. For a formula with nn variables and one solution, count 2n2^n checks and 2n/22^{n/2} iterations. For which nn do the two take the same time?

Hints
  1. Write each time as a power of 2 in seconds: the number of steps divided by the steps per second.
  2. The times are 2n−302^{n-30} and 2n/2−122^{n/2-12} seconds. Set the exponents equal.
Show the answer

Answer: 3636

n−30=n/2−12n - 30 = n/2 - 12 gives n/2=18n/2 = 18, so n=36n = 36. Both then take 262^{6} seconds; for larger nn the quantum computer wins.

Common slips

  • 1818: That solves n/2=30−12n/2 = 30 - 12 and stops. Doubling gives nn: the times are 2n−302^{n-30} and 2n/2−122^{n/2-12} seconds, equal when n−30=n/2−12n - 30 = n/2 - 12.
  • 8484: Check the signs: dividing by the speeds subtracts the exponents, so the times are 2n−302^{n-30} and 2n/2−122^{n/2-12} seconds.
  • 3030: At n=30n = 30 the classical computer needs only 1 second, while the quantum one needs 232^{3} seconds.

12 / 15 · Practice

Practice

Three items, each with new numbers when it comes back. Hints are there if you need them.

Check yourself

How many of the eight assignments x0x1x2x_0x_1x_2 satisfy (¬x0∨x1)∧(¬x1∨x2)(\lnot x_0 \lor x_1) \land (\lnot x_1 \lor x_2)?

Hints
  1. Which assignments make each clause false?
  2. A clause of two literals is false only when both literals are false: that fixes two variables and leaves the third free, so it rules out two assignments. Strike them out for each clause and count what is left.
Show the answer

Answer: 44

The satisfying assignments are 000, 001, 011 and 111: 4 of the eight.

Each clause rules out the assignments where all its literals are false. Clause 1, ¬x0∨x1\lnot x_0 \lor x_1, rules out 100 and 101. Clause 2, ¬x1∨x2\lnot x_1 \lor x_2, rules out 010 and 110. What is left: 000, 001, 011 and 111, so 4 assignments.

Common slips

  • 88: That counts the assignments where at least one clause holds. A CNF formula is an AND: every clause has to hold.
  • 66: That leaves out the last clause. Check it on the assignments that pass the others.

Check yourself

A Toffoli onto a work qubit ww that starts at 0, followed by an X on ww, should leave w=¬x0∨x2w = \lnot x_0 \lor x_2. Which controls does the Toffoli need?

  1. Aanti-control ○ on x0x_0, anti-control ○ on x2x_2
  2. Banti-control ○ on x0x_0, control • on x2x_2
  3. Ccontrol • on x0x_0, anti-control ○ on x2x_2
  4. Dcontrol • on x0x_0, control • on x2x_2
Hints
  1. On which single input of the two variables is the clause false?
  2. A control fires on 1, an anti-control on 0. Fire the Toffoli exactly where every literal is false.
Show the answer

Answer: C. control • on x0x_0, anti-control ○ on x2x_2

The clause is false only when x0=1x_0 = 1 and x2=0x_2 = 0, so the Toffoli fires there: control • on x0x_0, anti-control ○ on x2x_2. The X on ww then gives 1 everywhere else, which is the OR.

Why not the others

  • A. The literal ¬x0\lnot x_0 is false when x0=1x_0 = 1, so x0x_0 needs an ordinary control, which fires on 1.
  • B. This Toffoli fires when both literals are true, so after the X, ww is 0 exactly there: that is NOT (both true), not the OR. Fire the Toffoli on the one input that makes the clause false.
  • D. The literal x2x_2 is false when x2=0x_2 = 0, so x2x_2 needs an anti-control, which fires on 0.

Check yourself

Made-up speeds: a classical computer checks 2322^{32} assignments a second, and a quantum computer runs 2142^{14} Grover iterations a second. For a formula with nn variables and one solution, count 2n2^n checks and 2n/22^{n/2} iterations. For which nn do the two take the same time?

Hints
  1. Write each time as a power of 2 in seconds: the number of steps divided by the steps per second.
  2. The times are 2n−322^{n-32} and 2n/2−142^{n/2-14} seconds. Set the exponents equal.
Show the answer

Answer: 3636

n−32=n/2−14n - 32 = n/2 - 14 gives n/2=18n/2 = 18, so n=36n = 36. Both then take 242^{4} seconds; for larger nn the quantum computer wins.

Common slips

  • 1818: That solves n/2=32−14n/2 = 32 - 14 and stops. Doubling gives nn: the times are 2n−322^{n-32} and 2n/2−142^{n/2-14} seconds, equal when n−32=n/2−14n - 32 = n/2 - 14.
  • 9292: Check the signs: dividing by the speeds subtracts the exponents, so the times are 2n−322^{n-32} and 2n/2−142^{n/2-14} seconds.
  • 3232: At n=32n = 32 the classical computer needs only 1 second, while the quantum one needs 222^{2} seconds.

13 / 15 · Explain

Explain it

Explain it

A friend says: “Grover search with a SAT oracle tries all 2n2^n assignments at once, so SAT is easy on a quantum computer.” Explain what one oracle call really does, how many calls the search needs, and what that means for SAT.

Show a model answer

One call evaluates the clauses on every branch of the superposition, but all it leaves behind is a minus sign on the satisfying assignments; a measurement right after it would return one random assignment. Grover needs about π42n/M\tfrac{\pi}{4}\sqrt{2^n/M} calls to turn those signs into a high chance of measuring a solution. That is the square root of the 2n2^n checks of brute force, but 2n/22^{n/2} still grows exponentially: two more variables double the work. So Grover gives SAT a quadratic speed-up, not an efficient algorithm, and no quantum algorithm is known to solve NP-complete problems in polynomial time.

A good answer covers

  • One call only marks the satisfying assignments with a sign; it doesn’t read them out (a measurement would give one random assignment)
  • The search needs about π42n/M\tfrac{\pi}{4}\sqrt{2^n/M} calls, the square root of the brute-force count
  • 2n/22^{n/2} is still exponential in nn, so SAT doesn’t become easy
  • No known quantum algorithm solves NP-complete problems in polynomial time

14 / 15 · Mastery check

Mastery check

Check yourself

A formula has 30 variables, so there are 2302^{30} (about 1.1 billion) possible assignments, and exactly one of them satisfies it. Grover search runs with an oracle that checks the formula. About how many oracle calls does it need?

  1. A1: one call checks every assignment at once
  2. BAbout 30, roughly one per variable
  3. CAbout 26,000
  4. DAbout 540 million: half the assignments, as when checking them one by one
Show the answer

Answer: C. About 26,000

With N=230N = 2^{30} assignments and one solution, Grover needs about π4N=π4 215≈25,736\tfrac{\pi}{4}\sqrt N = \tfrac{\pi}{4}\,2^{15} \approx 25{,}736 calls. That is far fewer than the 2292^{29} checks brute force needs on average, but it is still exponential in the number of variables: two more variables double it.

Why not the others

  • A. One call does act on every assignment at once, but all it does is put a minus sign on the solution. A measurement right after it gives a random assignment. Turning that sign into a likely outcome takes about π4N\tfrac{\pi}{4}\sqrt N calls.
  • B. That would make SAT easy, and no quantum algorithm is known to do that. Grover’s count grows with the square root of the number of assignments, 230=215\sqrt{2^{30}} = 2^{15}, not with the number of variables.
  • D. That is the classical average, 2292^{29} checks. Grover gives a real gain: about π4230\tfrac{\pi}{4}\sqrt{2^{30}} calls, the square root of the classical count.

Check yourself

You want Grover search to solve a map-colouring puzzle (neighbouring countries get different colours). What do you need in order to build its oracle?

  1. AA quantum memory loaded with every candidate in advance
  2. BA circuit that checks the rules on any proposed solution
  3. CThe list of solutions, so that the oracle knows which inputs to mark
  4. DOnly the number of solutions
Show the answer

Answer: B. A circuit that checks the rules on any proposed solution

A search oracle is a circuit that checks the rules on whatever input it gets and flips the sign when they all hold. Building it takes the rules, not the answers.

Why not the others

  • A. Loading every candidate would take as many steps as checking them all classically. The superposition of all candidates comes from Hadamards on the input qubits; the oracle then computes the rules on it.
  • C. With the list in hand there would be nothing left to search for. The oracle only has to recognise a solution when it sees one: a circuit that checks the rules on its input marks exactly the solutions, and nobody needs to know in advance which they are.
  • D. The number of solutions helps you choose how many Grover iterations to run, but it can’t mark anything. Marking is done by a circuit that checks the rules on its input.

Check yourself

A Toffoli onto a work qubit ww that starts at 0, followed by an X on ww, should leave w=¬x0∨¬x1w = \lnot x_0 \lor \lnot x_1. Which controls does the Toffoli need?

  1. Aanti-control ○ on x0x_0, control • on x1x_1
  2. Banti-control ○ on x0x_0, anti-control ○ on x1x_1
  3. Ccontrol • on x0x_0, control • on x1x_1
  4. Dcontrol • on x0x_0, anti-control ○ on x1x_1
Hints
  1. On which single input of the two variables is the clause false?
  2. A control fires on 1, an anti-control on 0. Fire the Toffoli exactly where every literal is false.
Show the answer

Answer: C. control • on x0x_0, control • on x1x_1

The clause is false only when x0=1x_0 = 1 and x1=1x_1 = 1, so the Toffoli fires there: control • on x0x_0, control • on x1x_1. The X on ww then gives 1 everywhere else, which is the OR.

Why not the others

  • A. The literal ¬x0\lnot x_0 is false when x0=1x_0 = 1, so x0x_0 needs an ordinary control, which fires on 1.
  • B. This Toffoli fires when both literals are true, so after the X, ww is 0 exactly there: that is NOT (both true), not the OR. Fire the Toffoli on the one input that makes the clause false.
  • D. The literal ¬x1\lnot x_1 is false when x1=1x_1 = 1, so x1x_1 needs an ordinary control, which fires on 1.

Check yourself

To avoid uncomputing, a student gives every oracle call its own fresh work qubits: call 1 uses one set, call 2 another, and none is ever cleared. Does Grover search still find a solution with high probability?

  1. ANo: the leftover clause values still differ from branch to branch and block the interference
  2. BYes, but it needs twice as many iterations
  3. CNo, because the extra qubits make the search space bigger
  4. DYes: fresh work qubits start at 0, so nothing is left over to clean
Show the answer

Answer: A. No: the leftover clause values still differ from branch to branch and block the interference

Each call leaves ∣c(x)⟩\ket{c(x)} in its work qubits, a record that differs between branches. Branches carrying different records can’t interfere, so the diffusion step can’t build up amplitude on the solutions. Only uncomputing, which returns the work qubits to ∣0…0⟩\ket{0\ldots0} on every branch, removes the records.

Why not the others

  • B. More iterations don’t help: each call adds another record that tells the branches apart, and branches that can be told apart don’t interfere. The fix is to uncompute, not to iterate more.
  • C. The search space is still the 2n2^n assignments of the variables; nothing searches over the work qubits. The trouble is the records they keep, which differ between branches and block the interference.
  • D. They start at 0, but after the call they hold the clause values c(x)c(x), which differ between branches. Those records are entangled with the variables, so the diffusion step can no longer make the branches interfere. Uncomputing is what removes them.

Check yourself

Grover search over the 2122^{12} assignments of a 12-variable formula with exactly one satisfying assignment. How many iterations should it run?

Hints
  1. How does the best number of iterations depend on NN and MM?
  2. About π4N/M\tfrac{\pi}{4}\sqrt{N/M}, rounded to a whole number.
Show the answer

Answer: 5050

π4212/1=π44096≈50.27\tfrac{\pi}{4}\sqrt{2^{12}/1} = \tfrac{\pi}{4}\sqrt{4096} \approx 50.27, so 50 iterations.

Common slips

  • 6464: That leaves out the factor π4\tfrac{\pi}{4}. Each iteration turns the state by a fixed angle, and about π4N/M\tfrac{\pi}{4}\sqrt{N/M} turns reach the solutions.
  • 20482048: That is about how many checks a classical search needs on average. Grover needs about the square root of that: π4N/M\tfrac{\pi}{4}\sqrt{N/M}.
  • 5151: One more iteration overshoots: the state turns past the solutions and the success chance drops. Stop at the whole number nearest π4N/M\tfrac{\pi}{4}\sqrt{N/M}.

Check yourself

Grover search on four variables x0,…,x3x_0, \ldots, x_3 (qubits 0 to 3) ends with qc.measure(range(4), range(4)). The counts begin {'0101': 461, '0100': 458, '1010': 7, '1011': 4, …}. Which assignments, written x0x1x2x3x_0x_1x_2x_3, did it find?

  1. AOnly 1010: the most frequent string, read backwards
  2. BEvery string that appears in the counts
  3. C0100 and 0101, as printed
  4. D0010 and 1010
Show the answer

Answer: D. 0010 and 1010

Qiskit puts x0x_0 on the right, so read the strings backwards: '0100' is 0010 and '0101' is 1010. Two counts of nearly equal size mean two solutions, and checking each against the formula takes a moment.

Why not the others

  • A. The two big counts differ by a few shots in a thousand, which is sampling noise: both strings came up nearly half the time, so 0010 is a solution too.
  • B. Grover leaves a small chance of a wrong answer, and those few shots land on the other strings. Each candidate is quick to check against the formula; the two big counts are the solutions.
  • C. Qiskit prints classical bit 0, which holds qubit 0 and so x0x_0, as the rightmost character. Read each string backwards: '0100' is x0x1x2x3=0010x_0x_1x_2x_3 = 0010.

Check yourself

An honest oracle for a formula with 8 clauses of 2 literals each computes every clause into its own work qubit, ANDs the 8 clause qubits into the output, and uncomputes the clauses. Build each jj⁠-controlled X from 2j−32j - 3 Toffolis and count 7 T gates per Toffoli. How many T gates does one oracle call use?

Hints
  1. Count three parts: compute the clauses, the AND, uncompute the clauses.
  2. A 2-literal clause is a 2-controlled X: 2⋅2−3=12\cdot2 - 3 = 1 Toffoli. The AND is a 8-controlled X: 2⋅8−3=132\cdot8 - 3 = 13.
Show the answer

Answer: 203203

Clauses: 8×1=88 \times 1 = 8 Toffolis to compute and as many to uncompute. The AND: 1313. Total 16+13=2916 + 13 = 29 Toffolis, so 7×29=2037 \times 29 = 203 T gates per call.

Common slips

  • 147147: That leaves out the uncompute. The clause gadgets run a second time, in reverse, to clear the work qubits, and that costs as many Toffolis again.
  • 119119: The AND of 8 clause qubits is a 8-controlled X, which takes 2⋅8−3=132\cdot8 - 3 = 13 Toffolis, not one.
  • 9191: That counts only the AND. Every clause gadget is a multi-controlled X too, run once to compute and once to uncompute.
  • 2929: That is the number of Toffolis. Each one needs 7 T gates: 7×29=2037 \times 29 = 203.

15 / 15 · Recap

Recap

From memory

Before reading the summary, write down what you remember. Pulling it back from memory is what makes it last.

  1. How do you build an honest phase oracle for a CNF formula?

    Show the key points
    • One work qubit per clause. Each OR clause by De Morgan: a Toffoli fires where every literal is false (anti-control for xx, control for ¬x\lnot x), then an X on the work qubit
    • The AND of the clause qubits flips an output qubit in ∣−⟩\ket-, which kicks back (−1)φ(x)(-1)^{\varphi(x)} (or a multi-controlled Z does it directly)
    • Uncompute the clauses, so the work qubits return to ∣0…0⟩\ket{0\ldots0} and only the sign is left
  2. How many iterations does Grover run on it, and how do you read the answer?

    Show the key points
    • About π4N/M\tfrac{\pi}{4}\sqrt{N/M} for N=2nN = 2^n assignments and MM solutions
    • Measure the variable qubits; Qiskit prints qubit 0 on the right, so read the strings backwards
    • Check each candidate against the formula, which is quick
  3. What does the whole search cost, compared with brute force?

    Show the key points
    • Per call: 4m−34m - 3 Toffolis for mm two-literal clauses, 7 T gates each
    • About 2n/22^{n/2} calls against up to 2n2^n checks: a square root, still exponential
    • Slow quantum steps mean it wins only past a break-even size, such as n=40n = 40 in the worked example

Part 2 in review

This lesson closes Part 2. Across its eight lessons you have learned to:

  • approximate any operation with a small universal gate set, and count what a circuit costs;
  • write and run circuits as Qiskit code, read its bit order, and see where simulation runs out;
  • compute, copy and uncompute, so that work qubits never spoil interference;
  • count oracle queries, and find a hidden string with a single query;
  • uncover a hidden XOR pattern with exponentially fewer queries than any classical method, by solving equations over bits;
  • find a marked item among NN in about N\sqrt N steps, seen as a rotation;
  • boost any algorithm’s chance of success, even when you don’t know the odds;
  • turn a logic puzzle into an honest oracle, and work out what a quantum search really costs.

Until the next lessons arrive, your spaced reviews will keep Parts 1 and 2 fresh.

Key ideas

  1. SAT asks for an assignment that satisfies every clause of a CNF formula. Checking one is quick; brute force tries up to 2n2^n. SAT is NP-complete.

  2. An honest oracle checks the clauses on its input. An oracle written from the list of solutions presupposes the answer.

  3. An OR clause is one Toffoli by De Morgan: fire where every literal is false, then flip the work qubit.

  4. Compute, phase, uncompute: ∣x⟩∣0…0⟩→(−1)φ(x)∣x⟩∣0…0⟩\ket x\ket{0\ldots0} \to (-1)^{\varphi(x)}\ket x\ket{0\ldots0}. Leftover clause values would block the interference.

  5. Cost: Toffolis and T gates per call, times about π4N/M\tfrac{\pi}{4}\sqrt{N/M} calls. A square-root speed-up, still exponential, and ahead of brute force only for large nn.

Go further

Free resources for when you want more than this lesson covers.

Start the interactive lesson