Query-model algorithms
Two models of computation
Quantum algorithms are often analyzed in the query model, which differs from the ordinary computational model only in how the input is accessed.
Standard model
The algorithm receives the entire input.
Query model
The algorithm can only interrogate a black box.
In the standard model, the complete input is available from the start. The algorithm may read any part of it whenever it likes, perform arbitrary computations, and eventually produce an output. Cost: the total number of elementary computational steps.
In the query model, the function is hidden inside a black box called an oracle. The algorithm never sees the function directly. Instead, it repeatedly asks questions of the form “what is ?”, receives the answer, performs arbitrary computation, and decides which query to ask next. Cost: the number of oracle queries.
The query model isolates the cost of obtaining information from the cost of computation itself. This makes it possible to compare classical and quantum algorithms in a clean and mathematically precise way.
Examples of query problems
In the query model, the input is not a string—it is an unknown function . The algorithm cannot inspect the function directly. It can only ask questions like “” for inputs of its choice.
Hidden function
Flip the values below to change the hidden function .
Each problem asks a different question about the same hidden function. The answer updates automatically as you change the function.
Query gates
In a circuit model, access to the hidden function is represented by a query gate (or oracle gate). It behaves like an ordinary component, but its behavior is fixed by the unknown : given on its input wires it outputs . The function is supplied by the problem instance, not the algorithm, and each use counts as one query.
Query gates can be combined with ordinary logic gates just like any other circuit component. The circuit below solves the Parity query problem for a function with two possible inputs, and . It queries and , then outputs exactly when one of the two values is and the other is (odd parity).
Why study hidden functions?
Admittedly this model looks a bit weird at first — why lock the input inside a box and count questions instead of simply reading it? But many computational tasks — from searching a database to testing a physical device — can only access information by asking questions. The query model captures exactly this situation by treating the input as an unknown function that can only be queried.
Quantum query gates
Classical query gates output the value directly. That is convenient for classical circuits, but it cannot be used in quantum circuits.
The reason is that quantum gates must be unitary (and therefore reversible). A gate that simply replaces its input with is generally not reversible, since many different inputs may produce the same output.
So for the quantum circuit model we choose a different definition that is always unitary. The query gate for any function is defined, for all and , by its action on basis states:
In circuit form, leaves the top register holding and writes into the bottom register by XOR. Notice that the function value is added into the second register rather than replacing it — this small change makes the operation reversible for every possible function :
Starting the bottom register at makes the gate output directly, since .
The extra register may seem unnecessary at first, but it is what makes the oracle useful:
- it keeps unitary and reversible for every ;
- it lets the oracle act on a superposition of many inputs at once;
- and it preserves the phases that quantum algorithms exploit through interference.
Deutsch’s problem
Deutsch’s problem asks whether a function is constant or balanced. The function takes one bit as input and returns one bit as output, so there are only four possible functions.
Build a function
Flip the two outputs to define a function . There are exactly four possible functions. Try to discover them all.
Found 0 of 4 possible functions of the form :
| ? | |
| ? |
| ? | |
| ? |
| ? | |
| ? |
| ? | |
| ? |
The classical approach
A classical algorithm must evaluate both possible inputs: after seeing only one value, you still cannot distinguish a constant function from a balanced one.
Deterministic classical cost: 2 queries
Deutsch’s algorithm
Deutsch’s algorithm solves the same problem using only one query. It prepares two qubits, performs a single query to the oracle , applies one more Hadamard gate, and measures the first qubit — the measurement directly reveals , which is:
- for constant functions
- for balanced functions
Step through the circuit
- 1Prepare the two qubits in .
- 2Apply a Hadamard to each qubit.
- 3Apply the query gate — the single query.
- 4Apply a Hadamard to the top qubit.
- 5Measure the top qubit to read .
The Deutsch–Jozsa circuit
Deutsch’s algorithm works only for the simplest case: a function , which maps a single input bit to a single output bit. The Deutsch–Jozsa algorithm generalizes this idea to functions of the form for any , allowing the input to consist of any number of bits.
The purpose of the circuit is not to compute , but to extract information about the function as a whole. After one query, measuring the query qubits produces a bit string . The meaning of this string depends on the query problem: once we specify what property of we want to determine, we can interpret according to an appropriate decision rule.
The Deutsch–Jozsa problem
The Deutsch–Jozsa problem generalizes Deutsch’s problem: for an input function , the task is to output if is constant and if is balanced.
For these are the only two possibilities, so this is exactly Deutsch’s problem. When , however, some functions are neither constant nor balanced.
Build a function
Flip the four outputs to define any function and see which family it falls into.
of the four inputs map to — neither all of them nor half of them — so this function is neither constant nor balanced.
Input functions that are neither constant nor balanced are “don’t care” inputs. The promise excludes them, so on such a function an algorithm may output anything without being considered wrong.
The Hadamard transform
The Hadamard gate acts on the computational basis states like this:
The only difference between these two equations is the sign of the term. The factor captures this perfectly: it equals when and when . So we can combine both cases into a single expression:
Notice that the only difference between the two terms is their phase. The term always has a positive sign, while the sign of the term depends on the input bit . We can capture both cases with the exponent , where labels the basis state in the sum:
- for , we have , so , giving the positive sign of ;
- for , we have , so , giving the correct sign of .
Therefore, both terms can be written as a single summation:
From one Hadamard to many
The one-qubit Hadamard identity extends naturally to a register of qubits. Take an -bit input string whose bits all lie in , and write the basis state it labels:
Applying a Hadamard gate to every qubit means applying independently to each bit:
Every qubit now becomes a superposition of and . In the one-qubit formula the summation index was called , but here we need one such index per qubit, so we rename it to for the -th qubit. So the one-qubit identity, with renamed to and renamed to , reads:
Now substitute the one-qubit identity for each factor in the tensor product, using a separate index for each qubit:
By the multilinearity of the tensor product, the tensor product distributes over the sums, producing one term for every -bit string . The phase factors multiply together, so their exponents add. Thus maps to an equal superposition of all basis states , differing only in their phases.
Walking through the circuit
Let’s follow the state as it passes through each stage of the Deutsch–Jozsa circuit.
Step through the circuit
- 1Prepare the query qubits in and the target qubit in .
- 2Apply a Hadamard to every qubit.
- 3Apply the query gate — the single query.
- 4Apply a Hadamard to each of the query qubits.
- 5Measure the query register to get .
The Bernstein–Vazirani problem
Imagine that someone secretly chooses an -bit string .
You cannot see directly. Instead, you may query a function . For any input , the function looks only at the positions where the secret string has a . It counts how many of those positions also contain a in , and returns:
- if the count is odd,
- if the count is even.
What does mean?
The binary dot product works in two steps.
- Compare the corresponding bits of and .
- Count only the positions where both bits are . If this count is odd, the answer is ; if it is even, the answer is .
For example, compare the two strings bit by bit. Only the columns where both bits are contribute to the dot product. Click any bit to change it.
Mathematically, this is written as follows, where multiplication is ordinary binary multiplication (, otherwise ), and denotes XOR:
The quantum algorithm
Unlike Deutsch’s and Deutsch–Jozsa’s problems, where the goal is to learn one property of the function, the Bernstein–Vazirani problem asks for the entire hidden string .
Surprisingly, the quantum algorithm requires no new circuit. It uses exactly the same circuit as Deutsch–Jozsa:
- query qubits initialized to ,
- one target qubit initialized to ,
- Hadamard gates before and after a single query to the oracle .
The only difference is the promise on the function. Because , the measurement no longer reveals whether the function is constant or balanced — it reveals the hidden string itself.
Step through the circuit
The first three stages are identical to those of the Deutsch–Jozsa algorithm. Since we’ve already derived them, we’ll begin at the state , where the new promise on finally changes the outcome.
- 1Prepare the query qubits in and the target qubit in .
- 2Apply a Hadamard to every qubit.
- 3Apply the query gate — the single query.
- 4Apply a Hadamard to each of the query qubits.
- 5Measure the query register to read .
Simon’s problem
As in Bernstein–Vazirani, someone secretly chooses an -bit string , and the task is to recover it. What changes is how the function hides it.
The function no longer returns a single bit but a whole string, and no individual value tells you anything about . Instead, is written into the pattern of collisions: gives the same answer on two different inputs exactly when those inputs differ by .
The promise says that and collide only in the two ways it lists: either they are the same input, or one is the other shifted by . Which of those matters depends on whether is the all-zero string.
Case 1:
Shifting by changes nothing, since , so both branches of the promise say the same thing and the condition simplifies to
This is exactly the definition of one-to-one. On three bits, all eight inputs have different outputs, so a query never repeats a value.
Case 2:
Now is a genuinely different input from , and the promise forces the two to agree:
Every input is paired with exactly one partner, and the promise also rules out any other coincidence, so different pairs must have different outputs. The function is therefore two-to-one. With , the eight inputs collapse onto four outputs:
Nothing in a single answer points at . It shows up only once two inputs are found to share an output, and then .
The two cases are what makes the problem hard classically. Learning means finding a collision, and a classical algorithm has no way to force one: it can only keep querying inputs and comparing the answers it has already seen.
Simon’s algorithm
Simon’s algorithm consists of running the following circuit several times, followed by a post-processing step. The circuit is the familiar shape — Hadamards, one query, Hadamards, measurement — with two changes forced by the new function:
- the workspace is now qubits rather than one, since returns a string of bits;
- those qubits start in and carry no gates at all — not even a Hadamard.
Step through the circuit
- 1Prepare the query qubits and the workspace qubits in .
- 2Apply a Hadamard to each query qubit.
- 3Apply the query gate — the single query.
- 4Apply a Hadamard to each query qubit again.
- 5Measure the query register to read .
- 6Repeat steps 1–5, then solve the collected equations for — the one step that is classical, not the circuit.
Up to this point the practical value of these algorithms is thin, and the accounting is generous. The speedup is counted in oracle queries while everything around the query is assumed free. Someone still has to build the gate for , which can easily cost more than the queries it saves. The promise has to hold, and rejecting a function that fails it is roughly the problem you started with. Measurements come back noisy and runs have to be repeated. And all of it takes far more thought than the same job written in ordinary 0-1 bits.
Whether that changes further on, we will see. It is too early for disappointment either way. The road so far is a sequence of historical milestones, each adding a piece of the knowledge the later algorithms are built from:
- Deutsch showed quantum computation could outperform classical in principle: one query instead of two.
- Deutsch–Jozsa demonstrated an exponential separation in the query model, under a promise, and only against classical algorithms that must be exactly right every time.
- Bernstein–Vazirani found a separation that randomness cannot close, and applied recursively, a superpolynomial one.
- Simon introduced hidden-period techniques, and gave the first exponential separation against randomized classical algorithms.
All four are statements about the query model, where the only cost counted is the number of calls to the oracle, and where the function comes with a promise attached. Neither assumption holds outside it, and nothing here proves quantum computers are faster on ordinary inputs. The machinery does carry over though. Superposition, phase kickback and interference reappear in algorithms that are handed no black box at all. Whether that finally repays the trouble is an open question at this point.
The cost of classical algorithms
Measuring cost
In the query model there was exactly one thing to count. Outside it there is no oracle to call, so before any classical and quantum algorithm can be compared on a real problem, we need a yardstick that works for both.
An abstract view of computation
Whatever the computational model, the input and output are binary strings.
The middle box could be a Turing machine, a Boolean circuit, a quantum circuit or a Python program. Only the computation changes. Inputs and outputs remain binary strings, and numbers, vectors, matrices, graphs, or molecules all enter the computation through an appropriate binary encoding.
Input length
There is rarely a single standard encoding. We choose one, and the details matter less than they seem: converting between any two reasonable encodings adds only a small overhead. What the choice does determine is the input length: the number of bits in the encoded input. For a nonnegative integer written in binary,
| number | binary encoding | length |
|---|---|---|
| 0 | 0 | 1 |
| 5 | 101 | 3 |
| 12 | 1100 | 4 |
| 1 000 000 | 1111 | 20 |
| a 617-digit RSA modulus | 1 | 2048 |
This is the key idea. The input length grows logarithmically with the number it represents. A 2048-bit input therefore describes a number close to . An algorithm that tests every divisor up to performs about operations on an -bit input. It may look efficient when measured against , but it is exponential when measured against the true input size .
Elementary operations
The cost of a circuit is measured by the number of elementary gate applications it performs. Which gates are considered elementary is a modeling choice: we first fix a gate set, and each application of a gate from that set counts as one computational step. The set does not have to be minimal—some gates may themselves be implementable using other gates in the same set.
We count FANOUT as a gate. It is often treated as free, but making it explicit highlights an important contrast: classical circuits can copy bits freely, whereas quantum circuits cannot.
This gate set is universal: any unitary operation can be approximated to arbitrary accuracy using only these gates.
Size and depth
The size of a circuit is the total number of gates in it. Its depth is the largest number of gates on any path from an input wire to an output wire. Size corresponds to sequential running time, while depth corresponds to parallel running time.
Cost as a function of input length
A circuit has a fixed number of input wires, so it accepts inputs of only one length, and its cost is simply its size, . An algorithm, however, must work for inputs of arbitrary length. It is therefore represented by a family of circuits , where handles -bit inputs. The cost of the algorithm is then the size of the circuit for each input length:
For example, a classical factoring algorithm is a family of Boolean circuits, while a quantum factoring algorithm is a family of quantum circuits. Both solve the same problem on -bit inputs, differing only in the gate set they use.
This lets us compare algorithms by how grows with the input length. An algorithm is considered efficient if is bounded by a polynomial in .
Cost analysis: integer addition
Now that cost is defined as a function of the input length, we can work through a complete example. The simplest one is integer addition: given two integers and , compute their sum . Both inputs are provided in binary.
The algorithm itself is familiar from elementary school. What changes is the model of computation. Instead of describing the sequence of arithmetic steps, we must build the algorithm as a Boolean circuit from elementary gates and determine its cost. Later, we will construct the same algorithm on a quantum circuit and compare how the resource requirements differ.
The algorithm
Binary addition follows the same schoolbook procedure as decimal addition. Starting with the least significant bit, each column adds the two input bits together with the carry from the previous column, producing a sum bit and a new carry for the next column.
The important observation is that every column performs exactly the same computation. It receives three input bits—the operand bits and , and the incoming carry —and produces two output bits: the sum and the outgoing carry .
Building the Boolean circuit
The addition algorithm consists of one operation repeated for every bit position. We therefore start by building a circuit for a single column. Once that building block is complete, the full adder is obtained simply by connecting copies of it together.
Every column of the addition except the least significant one—bit , where there is nothing to carry from—must also handle an incoming carry. Starting from a half adder, we add a second half adder to incorporate the carry, then combine the two possible carry outputs with an OR gate. The result is a full adder, implementing the three-input, two-output function performed by every column.
The complete adder is built by repeating the same full adder circuit, with the carry propagating from one bit to the next.
Count the gates
An -bit adder is one half adder and full adders, so
Whether that constant comes out as 21, or 31, or something else again depends on the gate set and on how the XOR is expanded, and it is not what we are after. What the construction establishes is that there exists a family of Boolean circuits, where adds two -bit nonnegative integers together, such that .
Asymptotic notation
The exact number of gates depends on implementation details such as the gate set or the choice of intermediate operations. These differences affect only constant factors, while the overall growth of the algorithm stays the same. Asymptotic notation describes that growth by ignoring constant multipliers and lower-order terms.
The most commonly used notation is Big O, which gives an upper bound on the growth rate of a function. For two functions and , we write that if there exists a positive real number and a positive integer such that for all .
Growth classes
Examples
Polynomial, Subexponential, and Exponential Growth
These three names describe how an algorithm's cost grows with the input size. The chart shades these regions on its log scale.
Polynomial — for a fixed . This is the usual boundary for what we call efficient.
Subexponential — : the exponent grows more slowly than . A stricter definition requires for every . The number field sieve is subexponential under the first definition, but not under this stricter one.
Exponential — : the exponent grows linearly with . In particular, an algorithm that is not subexponential is not automatically exponential. There is a gap between the two classes.
The exponential-time hypothesis (ETH) conjectures that NP-complete problems have no subexponential-time algorithms.
Cost analysis: integer multiplication
The next example is one step up from addition: given two integers and , compute their product . Both inputs are again provided in binary. As with addition, the algorithm itself is familiar. The task is to express it as a Boolean circuit and determine how its cost grows with the input length.
The algorithm
Binary long multiplication follows the same procedure as decimal long multiplication. For each bit of , we form a partial product by either copying or producing a row of zeros, depending on whether that bit is or . Each partial product is then shifted according to the position of the corresponding bit of . Adding all of these shifted rows gives the final product.
The key observation is that every bit of every partial product depends on exactly two input bits: one bit from and one bit from . This gives us a simple building block for the first stage of the circuit.
Building the Boolean circuit
For a pair of bits and , the corresponding partial-product bit is exactly when both bits are . This is precisely the function computed by an AND gate.
We therefore obtain all partial products by arranging these AND gates in a grid. For two -bit inputs, there is one gate for every pair , giving an array and therefore AND gates.
This produces the partial products, but they still have to be added together. Here we can reuse the -bit adder from the previous example. The shifted partial products are added one after another, requiring such additions.
Count the gates
Counting the two stages: the array contributes AND gates, and the summation contributes adders of gates each. The total is
So there is a family of Boolean circuits, where multiplies two -bit nonnegative integers, with . By the standard multiplication algorithm, there are Boolean circuits of size for multiplying -bit integers.
More generally, the same array argument with an grid gives circuits of size for multiplying an -bit integer by an -bit integer.
Faster multiplication: convolution and the Fourier transform
Schoolbook multiplication costs , and for a long time that was taken to be optimal. In 1960, Karatsuba showed that it was not, using divide and conquer to reduce multiplication to a smaller number of multiplications.
The same search for structure leads further: the pairwise products of schoolbook multiplication form a convolution, and the Fourier transform provides a way to compute that convolution efficiently.
Multiplying in blocks
An -bit integer can be split into blocks of bits, with each block treated as a single digit in base . Thus , and .
Schoolbook multiplication of these block digits forms every product , giving block products. This is not a saving by itself: larger blocks give fewer products, but each product is a multiplication of wider numbers.
The reason for changing to blocks is that they make the structure of the product visible. A cell of the array represents . Summing over all cells therefore gives . The index sum determines where each product contributes: cells with the same index sum multiply the same power of , so their products can be added together.
Given this structure, the question is therefore how to combine the products more efficiently, rather than compute and handle each one separately.
Convolution
From the product table above, we already know that products with the same index sum belong together. Let . Then the product can be written as . The sequence is the convolution of the block sequences and .
So the cells of the multiplication array collapse into just diagonal sums:
Calculating convolution
The same sum can be pictured two ways: as a diagonal in the product table above, or by sliding the reversed blocks under the blocks.
d₀ = a₀c₀ = 2
Nothing has become faster yet. The same pairwise products still appear in the definition of the convolution.
But we have changed what we are trying to compute. Schoolbook multiplication computes every and immediately assigns it to a diagonal. The individual products are discarded after contributing to their diagonal sum. The result we actually need is only .
So the problem can now be stated precisely: can we compute all the convolution coefficients without computing all products individually? That is the problem the Fourier transform will solve.
Another way to compute convolution
So far, the coefficients have been a sequence of numbers attached to powers of the base in . Instead of fixing the base at , leave it as a variable: the same structure becomes a polynomial, which for the blocks above is .
At the same time, the two multiplicands can be written as polynomials too— and . Multiplying them gives . So the coefficients of are exactly the convolution coefficients we want: we have simply turned the two input sequences into polynomials and the convolution into their product.
Now comes the useful part: a polynomial can be represented in another way—not by its coefficients, but by its values at enough distinct points. A degree- polynomial is completely determined by such values. In this representation, multiplication becomes much simpler. At every point , so we can evaluate and , multiply the corresponding values, and obtain the values of . There are no cross terms: just one ordinary multiplication per point.
Since has degree , values are enough to recover all its coefficients. The strategy is therefore:
at x₀
Points → recovered coefficients of D(x)
2, 5, 7, 15, 10, 11, 6
We have recovered all the convolution coefficients—but we have not made the computation faster yet. Evaluating the polynomials and interpolating the result still costs when done naively. The key question is therefore not whether this representation works, but whether we can choose the evaluation points so that the evaluations themselves can be computed efficiently—that is where the Fourier transform enters.
Choosing the evaluation points
We want evaluation points where one evaluation can reuse work from another. A natural pair to try is and .
The two points differ only in the sign of . To make that useful, sort the coefficients of by whether their position is even or odd. Call the two halves and ; both are polynomials in , and —for example, . Now the advantage is visible: replacing by leaves unchanged, so the even half stays the same while the odd half changes sign, .
Thus both and can be calculated from the same two quantities, and . Once these are known, the two results require only one multiplication and two additions: form once, then add it to and subtract it from . The important part is that and each have half as many coefficients as . The same rule therefore applies to them, and to their halves in turn—each split naming its pieces by the choices that made them, so that is the even half of ’s odd half. Repeating this keeps halving the size of the problem.
The caveat is that we have only used the pairing once. To keep saving work, the points left after that first split must themselves form pairs, so that the same idea can be applied again. Real numbers do not work. Once we square them, all points become nonnegative, so the pairing is lost. We therefore move to the complex plane.
The roots of unity have exactly the structure we need: , . They are evenly spaced around the unit circle. Each point has an opposite partner, , and squaring sends each pair to the same point. The resulting points are again evenly spaced, so the pairing survives and the process can repeat: .
We now have evaluation points, paired as and . To make each pair share the same work, we separate into its even- and odd-power terms: .
This rewrite makes the input to both smaller polynomials. For each pair , this input is the same because .
Thus the original points give only distinct inputs for and : .
We can therefore evaluate the two smaller polynomials using just these points.
From coefficients to values at the roots of unity
We have now split the polynomials down to their individual coefficients. The next step is to reverse the process: combine the pieces back up to obtain the values of and at the chosen roots of unity. These values are exactly what we need to multiply the polynomials pointwise.
1. Split down to individual coefficients
We apply the same recursive split to both and , until every branch contains a single coefficient.
For , the leaves are , and .
For , following the same process as with , we obtain , and .
These and are now the individual coefficients that we recombine upward.
The coefficients themselves have not changed. They are still the original coefficients of the two polynomials. What has changed is how they are organized. At each split, we separate even and odd powers, and the resulting branches record these choices. The tree makes this recursive structure explicit. We can then reverse the same structure to combine the coefficients and evaluate the polynomials at all the roots of unity.
2. Recombine upward
Reverse the same tree. At each level, combine the even and odd pieces until we have evaluated both polynomials at all chosen roots of unity:
At each point , multiply the two values:
| Point | |||
|---|---|---|---|
3. Interpolate
The values determine the degree- product uniquely. Interpolating them gives
So we have multiplied the two polynomials without forming all coefficient products.
The complete process is:
But there is still one important question: how did we evaluate the polynomials at all those roots of unity efficiently?
Naming the operation: DFT and FFT
The operation we have just performed—taking the coefficients of a polynomial and evaluating it at the roots of unity—is the Discrete Fourier Transform (DFT). For , the DFT takes and produces .
The recursive even/odd splitting above is what makes this evaluation fast. Recall that while . We evaluate the smaller polynomials and once; if their values are and , the paired results are and . This combination is one butterfly.
Because the roots of unity are paired as and , squaring them gives the points needed by the smaller transforms. The same split therefore repeats, . The recursion does not merely divide the problem into smaller pieces: each smaller problem has exactly the same structure as the original one.
The Fast Fourier Transform (FFT) is this recursive algorithm for computing the DFT efficiently.
At each level, the butterflies combine the results of the two half-size transforms. There are butterfly operations per level and levels, giving . The same applies to , so we can write the complete multiplication algorithm compactly as
The inverse transform takes the values back to the coefficients , which are exactly the convolution coefficients we wanted. Thus the Fourier transform turns convolution into pointwise multiplication, The pairwise products have been replaced by two fast transforms, pointwise products, and one inverse transform.
The Schönhage–Strassen algorithm
The Fourier transform gave us a fast way to multiply polynomials. But originally we set out to multiply integers, and for them there are still open questions:
- Can the transform be made exact? The roots of unity it evaluates at are complex numbers, and their coordinates are irrational, so complex arithmetic is only ever approximate—but a product of integers has to come out exactly.
- Can the leftover multiplications be removed? The pointwise products are still multiplications of integers. The transform has shrunk their operands—to about bits each—but has not made them go away.
And the Schönhage–Strassen algorithm closes both.
The first fix is to change where the arithmetic happens. Instead of the complex plane, run the transform inside modular arithmetic—the integers modulo . There , so . The number therefore behaves as a -th root of unity: its powers close into a cycle, with the opposite points satisfying .
The highlighted pair, opposite on the ring:
Square both. Since , the extra factor drops and they meet:
Both land on the same point, —just as and square to . That collapse halves the points, and the transform recurses on what remains.
This change solves two problems at once. The transform is now exact, because nothing is represented by an approximate complex number. And every root of unity is a power of , so multiplying by one is just a shift of the bits, with the part that runs off the top folded back with a minus sign. The transform therefore needs only additions and shifts, and costs bit operations.
The second fix is to recurse. Each of the pointwise products is a multiplication of much smaller integers—the very problem we began with, in miniature. So we solve those products using the same algorithm. This recursion is the heart of Schönhage–Strassen.
To analyze the cost, one free parameter remains: how many blocks should we use? Cutting an -bit integer into blocks gives blocks of about bits, and the transform turns the multiplication into pointwise multiplications of numbers that size. There is a trade-off: fewer blocks mean larger pointwise multiplications, more blocks mean a longer transform. Balancing the two costs gives , so each block has about bits. At one level of the algorithm we therefore have:
- an -bit integer split into about blocks of about bits each;
- two forward transforms and one inverse transform, costing additions and shifts;
- about pointwise multiplications;
- each pointwise multiplication multiplying two -bit numbers, producing a result of about bits.
That last point is crucial. The recursive problems are multiplications of roughly -bit numbers, and there are about of them, so the recursive part contains bits in total—only a constant factor more than the input bits. This gives the recurrence
where the first term is the work done by the transforms and the second is the cost of the recursive multiplications. Now look at what happens as we recurse: each level square-roots the operand size, . At first this may look as though the recursive work should become dramatically smaller, but there are more and more subproblems at each level, and the number of bits across all of them grows by the same factor that the logarithm of their size shrinks. So, up to constant factors, each level still costs :
| Level | Operand size | Bits in total | Transform work |
|---|---|---|---|
| 0 | |||
| 1 | |||
| 2 | |||
| r |
The only thing left to determine is how many levels there are. Taking a square root halves the exponent, so after levels the operands are about bits wide, and we stop when that reaches constant size. Taking logarithms, the condition reads , or , so . Each of those levels costs , giving
That is where the second logarithm comes from: the transform itself costs only bit operations, and the extra is the price of repeating that work over levels of recursion.
For the small example above, all of this machinery is obviously overkill. Splitting, padding, transforming, and rebuilding the result carry their own overhead. The advantage appears only for sufficiently large inputs, when replacing pairwise block products with transform work saves more than that setup costs.
Beyond Schönhage–Strassen
Schönhage–Strassen remained the asymptotically fastest known integer multiplication algorithm for decades. In 2019, Harvey and van der Hoeven presented Integer multiplication in time O(n log n), an algorithm of complexity , which is conjectured to be optimal up to constant factors.
Cost analysis: integer division
Given two integers and , integer division computes a quotient and a remainder such that with . As before, the inputs are given in binary. But division differs from addition and multiplication in an important way: it must make a decision at each step. Given the current partial remainder, it has to determine whether fits and, depending on the answer, either subtract or leave the remainder unchanged.
A Boolean circuit cannot branch on this decision. Instead, it has to implement the decision itself using logic gates. This makes the cost of division more interesting to analyze than the straightforward bit-by-bit operations we have seen so far.
The algorithm
Decimal long division is awkward because, at each step, we must determine the next quotient digit from several possibilities. In binary, that choice disappears: the next quotient bit can only be or . So each step reduces to a single question: does the divisor fit into the current partial remainder?
The algorithm—shift and subtract—processes the bits of from most significant to least significant. Start with . At each step, bring in the next input bit by shifting the current remainder left by one position, , then compare with :
- if , subtract and set the quotient bit to ;
- if , keep unchanged and set the quotient bit to .
The updated value becomes the remainder for the next step.
After all bits have been processed, the quotient bits form , and the final value of is the remainder.
The important point for the cost analysis is that never becomes arbitrarily large. Since , we have , so needs at most one bit more than . The numbers involved therefore stay within essentially the same width throughout the algorithm.
Building the Boolean circuit
Every step performs the same computation, so we only need to design one circuit and then repeat it once for each bit of . At each step, the circuit must do two things: compute , and decide whether to keep that result or keep instead.
The subtraction can reuse the adder from the addition example. Using two’s complement, , so we invert every bit of and set the adder’s carry-in to . Its carry-out gives the quotient bit : it is when the subtraction can be kept, and when we must keep the original remainder.
We still need to implement this choice:
A circuit cannot skip the subtraction when ; it computes in every case and then uses to choose which result to keep. For each bit, a small multiplexer selects between the two candidate results, . When the first term passes the subtraction result through; when the second passes the original through. The same selection circuit is applied independently to every bit.
The multiplexer uses a constant number of gates per bit, so for -bit numbers it contributes gates. Together with the -gate subtractor, one division step therefore still uses only gates.
This one step is the whole algorithm. We repeat the same circuit once per bit of , passing the remainder from one step to the next and collecting the quotient bits as they are produced—just as the adder was built by repeating a full-adder stage.
Count the gates
The algorithm performs one division step for each of the bits of . Each step processes bits and uses gates: for the subtraction and for the bit-by-bit selection. Repeating this step times gives
So there is a family of Boolean circuits, where divides one -bit nonnegative integer by another and returns both the quotient and the remainder, with . Counting the two widths separately, as in the figures above, an -bit dividend and an -bit divisor give steps of gates, hence circuits of size .
A faster algorithm
Schoolbook division has the same cost as schoolbook multiplication. But division does not fundamentally require repeated subtraction: it can be reduced to multiplication. The key is the reciprocal of the divisor. Since , we can divide by by first computing , then multiplying by ; a final correction recovers the exact quotient and remainder.
To compute efficiently, we use Newton’s method, , whose approximation to roughly doubles its number of correct bits each iteration. Since the precision grows as the approximation improves, the resulting costs form a geometric series, , where is the cost of multiplying two -bit integers.
Thus division can be performed in bit operations: asymptotically, division costs no more than multiplication. Any fast multiplication algorithm therefore gives a fast division algorithm— Schönhage–Strassen multiplication brings division to , and the more recent Harvey–van der Hoeven algorithm improves it to .
Cost analysis: greatest common divisor
Given two nonnegative integers and , their greatest common divisor is the largest integer that divides both. The classic method for finding the gcd is the Euclidean algorithm. It repeatedly replaces until the remainder becomes . The last nonzero remainder is the gcd.
Two things determine the cost: the cost of one division and the number of divisions. Each Euclidean step computes a remainder , using the division circuit from the previous section, and a division of two -bit numbers costs gates. A simple analysis would say that the algorithm takes divisions, giving . It does indeed take only steps: every two steps, the current remainder is at most half the value from two steps earlier, so the numbers lose at least one bit every two steps. But is too loose. Not every division is an -bit division. As the numbers get smaller, later divisions become cheaper, so we need to account for the size of each quotient.
Suppose the -th division has quotient , and let be the number of bits in that quotient. Schoolbook division performs one compare-and-subtract operation for each quotient bit, and each such operation costs gates, so the -th division costs and the whole run costs . The key question is therefore: how large can the total number of quotient bits be?
Bounding the total quotient size
Let the sequence of values produced by the Euclidean algorithm be , , , where the -th division is and is the remainder. Since the remainder is nonnegative, the right-hand side is at least on its own, so : each step shrinks the current value by at least a factor of . Applying this inequality repeatedly gives
The last nonzero value is the gcd, so and the right-hand side is at least the product of the quotients alone: . This is the crucial bound—although there may be many divisions, their quotients cannot all be large, because their product is limited by the original input. Taking logarithms converts that product into a sum:
the last step because has bits, so . Now relate this to the actual number of quotient bits. A number with bits sits between the two neighbouring powers of two, , and taking logarithms of the left inequality gives , which means . The is the rounding up to a whole number of bits, and each division pays it once.
Summing over the divisions, . The first sum is less than , and there are only Euclidean divisions, so the second contributes another , giving . So although the algorithm may perform divisions, the total number of quotient bits across all those divisions is only . The total cost is therefore
Thus, with schoolbook division, the Euclidean algorithm costs gates. This is the same asymptotic cost as a single -bit multiplication or division using schoolbook arithmetic. With faster multiplication and division algorithms, a recursive version of the Euclidean algorithm can be implemented in bit operations, where is the cost of multiplying two -bit integers—a count of bit operations rather than of circuit gates.
Cost analysis: modular exponentiation
Modular exponentiation computes for nonnegative integers , and a modulus , each at most bits long. It is the core operation of RSA and Diffie–Hellman. The question here is not just how to compute it, but how the cost grows with .
Multiplying by repeatedly is inefficient for two reasons. It takes about multiplications, and an -bit exponent can be as large as , making the number of multiplications exponential in the input length. It also constructs the full integer , whose intermediate values can grow exponentially large — even though the final result modulo is smaller than . An efficient algorithm must avoid both problems.
The efficient method is square-and-multiply. Instead of multiplying by once for every unit in , we use the binary representation of to build the required power by repeated squaring. Writing the exponent as with gives
The powers are each obtained by squaring the previous one, so generating all of them takes squarings. We then multiply together only the powers corresponding to the -bits of , requiring at most another multiplications.
Crucially, we reduce modulo after every multiplication. Every intermediate value therefore stays below , so we never construct the enormous integer . The entire computation uses at most modular multiplications, giving a total of modular multiplications.
Cost of one modular multiplication
A modular multiplication takes two values, multiplies them, and then reduces the product modulo . Because , we can reduce after each multiplication and never need to store values larger than . Since is represented using at most bits, each value involved in a modular multiplication has at most bits.
Multiplying two -bit values produces a product of at most bits. From the multiplication circuit above, this costs gates. We then reduce the -bit product modulo , and the division circuit also costs gates. Therefore one modular multiplication costs gates.
Total cost
Square-and-multiply uses modular multiplications, and each modular multiplication costs gates. Therefore .
Thus there is a family of Boolean circuits such that computes for inputs of at most bits, with . In other words, modular exponentiation can be implemented by a family of polynomial-size Boolean circuits.
The bound uses the basic multiplication and division circuits described above. Replacing them with faster algorithms improves the bit-operation cost to , where is the cost of multiplying two -bit integers.
Cost analysis: integer factorization
Given an integer , integer factorization finds its prime factorization: the unique representation , where the are distinct primes and the are positive integers. Here is given in binary using bits, and we ask the same question as in the previous blocks: how does the work required to recover the answer grow with the input length ?
For the arithmetic problems considered so far, we could construct Boolean circuits whose size grows polynomially with : , , or , depending on the operation. But for factorization no polynomial-size circuit family is known so far—perhaps there is one, but we do not know.
The practical difficulty is illustrated by the RSA Factoring Challenge. One of its targets, RSA-1024, was a 1,024-bit number with a US$100,000 prize. The challenge ended in 2007 with RSA-1024 still unfactored, and the remaining prizes were withdrawn. The largest RSA challenge number that has been factored is RSA-250, an 829-bit number factored in February 2020 using the general number field sieve. The computation required roughly 2,700 CPU core-years.
Trial division
The simplest approach is trial division: test possible divisors one at a time. If is composite and both and were greater than , then their product would be greater than , which is impossible. So every composite has at least one factor . We therefore only need to test prime candidates . For each candidate, compute : a remainder of means that is a factor. Divide it out and repeat the process on the quotient until the remaining factor is prime.
The worst case for trial division is an input with no small factor. Since an -bit input satisfies , we have . Trial division may therefore need to test up to candidate divisors. Each test uses the -gate division circuit built above, giving
Testing only prime candidates reduces the number of tests: the number of primes below is about . So restricting the search to primes saves roughly a factor of , but the exponential term remains. Trial division is therefore still exponential in the input length.
A congruence of squares
Trial division looks for a factor directly: try , then , then , and so on. For a hard case—a large integer with no unusually small factor—general-purpose factoring methods take a different approach. Instead of searching for a divisor, they construct a relation from which a divisor can be extracted.
That relation is a congruence of squares. Suppose we find two numbers and such that . In other words, and leave the same remainder when divided by . Therefore, .
So divides the product of and . If is composite, its factors can be distributed between these two terms, and we can often recover one of them by computing .
different as ordinary integers, equal after reduction
so the difference is a multiple of 737
and the gcd with 737 pulls one factor out of the product
a factor, found without dividing by anything
The gcd itself is cheap: the above costs gates. The difficult part is finding the pair in the first place.
The quadratic sieve
We want to find . The quadratic sieve approaches this indirectly. Instead of trying to find directly, it looks for many values of that factor completely into small primes. These are called smooth values. Once enough smooth values have been collected, we can combine them so that their product becomes a perfect square. That gives us the second square.
The list of small primes is called the factor base, and every value that factors completely over it is kept as a relation.
The table's parity column records whether the exponent of each factor-base prime is odd or even. With factor base , for example, has odd exponents for and , and even exponents for and , so its parity vector is . Parity is all we keep, because a number is a perfect square exactly when every exponent in its factorization is even — whether an exponent is or makes no difference to that question.
Parity rows add the way values multiply. Multiplying two values adds their exponents, so it adds their parity bits mod 2, one prime at a time: . A prime used an odd number of times in each of the two values is used an even number of times in their product, so the two s cancel. A set of rows adding to all zeros is therefore a set whose values multiply to a perfect square, and finding such a set is the only thing the parity column is for.
Both halves of the congruence come out of that one set. Multiplying the chosen values of gives the left-hand root; squaring it replaces each one by its residue from the table, so is congruent to the product of those residues — the product just shown to be a square. The right-hand root is that square's root, and nothing has to search for it: halving every exponent in the factorization writes it down directly, which is possible only because the parities were all even. Reduce mod and is in hand, with the gcds left to finish.
| factors into | parity |
|---|
| 28 | 47 | × | |
| 29 | 104 | × | |
| 30 | 163 | × | |
| 31 | 224 | click (1,0,0,1) | |
| 32 | 287 | × | |
| 33 | 352 | × | |
| 34 | 419 | × | |
| 35 | 488 | × | |
| 36 | 559 | × | |
| 37 | 632 | × | |
| 38 | 707 | × | |
| 39 | 47 | × | |
| 40 | 126 | click (1,0,0,1) | |
| 41 | 207 | × | |
| 42 | 290 | × | |
| 43 | 375 | click (0,1,1,0) | |
| 44 | 462 | × | |
| 45 | 551 | × | |
| 46 | 642 | × | |
| 47 | 735 | click (0,1,1,0) | |
| 48 | 93 | × | |
| 49 | 190 | × | |
| 50 | 289 | × | |
| 51 | 390 | × | |
| 52 | 493 | × | |
| 53 | 598 | × | |
| 54 | 705 | × | |
| 55 | 77 | × | |
| 56 | 188 | × | |
| 57 | 301 | × | |
| 58 | 416 | × | |
| 59 | 533 | × | |
| 60 | 652 | × | |
| 61 | 36 | click (0,0,0,0) | |
The demo keeps the numbers small enough to show the bookkeeping: candidate values, smooth relations, parity rows, and the final gcds. A real quadratic sieve uses the same logic at a scale where hand-picking rows is impossible. It locates smooth values with an actual sieve—the operation the algorithm is named for—and then uses linear algebra over to find a set of relation rows whose parity sum is zero.
Note the tradeoff: a larger factor base makes smooth values easier to find, since more primes can divide them. But it also makes each parity row wider, increasing the size of the linear system and the number of relations needed before a dependency is guaranteed. The running time therefore depends on choosing a factor-base size that balances the cost of finding relations against the cost of solving the resulting linear system.
The general number field sieve
The general number field sieve (GNFS) improves on the quadratic sieve by changing how its smooth relations are constructed. In the quadratic sieve, we look for smooth values among , which are roughly as large as . As grows, smooth values become increasingly rare.
GNFS takes a different route: instead of searching for smooth values of roughly size , it constructs smaller values and looks for pairs that are smooth. That makes smooth relations much easier to find, and is the key reason GNFS can handle much larger integers.
The search begins by choosing a polynomial of degree with a root modulo , so that . Instead of testing single values of , GNFS tests coprime pairs of integers : it searches over a finite range, sweeping the integer grid within it and keeping the pairs for which . From each pair, it constructs two integers: on the ordinary integer side, and on the number-field side. These are the two values we test for smoothness. If both factor completely over their respective factor bases, the pair gives a smooth relation and is kept.
Choosing may look like the difficult part, but constructing a suitable polynomial is surprisingly straightforward. Fix a degree , choose , and write in base . Use those base- digits as the coefficients of . Then, by construction, , so in particular . That is exactly the property GNFS needs.
The only choices are the degree and the factor base. The degree determines m, and m determines the coefficients.
Polynomial form of the line above, with x in place of m.
This is why we constructed f this way: m = 9 is a root of f modulo N, which links the two sides of the GNFS construction.
One thing to notice is that GNFS is not necessarily faster than the quadratic sieve on small numbers. It does more work per relation, but that extra cost is offset by its better asymptotic scaling as grows. Only for sufficiently large does GNFS become the faster method.
The cost of GNFS
Almost all of the work in GNFS goes into two jobs. The first is collecting relations: sweep the grid of candidate pairs , test the two values each pair produces, and keep the pairs where both factor completely over the factor bases. The second is the linear algebra: take the relations that survived and find a set of parity rows summing to zero, which is what turns a pile of relations into a congruence of squares. Neither job can be skipped — the first produces the raw material and the second extracts an answer from it — so the running time is the sum of the two.
Both jobs are governed by one number: the smoothness bound , the largest prime allowed in the factor bases. is the knob we can turn, and it pulls the two jobs in opposite directions. Turn it up and each value has more primes available to factor into, so relations become easier to find; but the factor bases grow with it, and every extra prime is another column in the matrix the second job has to solve.
How many primes is that? There are about primes below . The logarithm moves that count by far less than the choice of itself does, so from here on we drop it and speak of about factor-base primes.
Each surviving relation becomes one row of the relation matrix, recording which factor-base primes occur an odd number of times, and each factor-base prime is one column. A set of rows summing to zero is guaranteed once there are more rows than columns, so with about columns GNFS needs about relations, plus a small surplus so that the dependency it finds is a usable one. That is where the first job's target comes from: not as many relations as possible, but about of them.
What one relation costs depends on how often a candidate turns out to be smooth. Write for the size of the values being tested and set . This measures the tested value against the smoothness bound: it is roughly how many factors of size it takes to build a number of size . When is small the value is barely larger than the primes allowed to divide it, and smoothness is common. When is large the value has to be assembled out of many small primes at once, which is rare.
For a random integer of size , the Dickman function puts the chance of being -smooth at about . Turn that probability into work: one success in every candidates means about candidates tested per relation kept, and about candidates tested to collect the relations we need. This step is heuristic. The values GNFS tests come out of a polynomial and are not random integers, but they behave closely enough to random ones for the estimate to hold up in practice.
The second job works on what the first produced: about relations, so about rows, against about factor-base primes, so about columns — a matrix roughly . It is a sparse one, since a single relation is divisible by only a handful of factor-base primes and almost every entry in its row is zero. Sparse methods exploit that and cost roughly , instead of the that ordinary elimination would spend on a dense matrix of that size. Real implementations are more delicate; is the simplified model we carry through the argument. The two costs together are
Everything that follows is an argument about how to choose in that one equation. Push down and becomes negligible, but grows and grows much faster still: smooth values turn rare and the sieve spends a long time looking for them. Push up and relations arrive quickly, but the matrix that has to absorb them grows quadratically.
| smoothness bound B | finding relations | linear algebra |
|---|---|---|
| small | expensive — smooth values are rare | cheap — few columns to solve |
| large | cheap — smooth values are common | expensive — many columns to solve |
| balanced | the two costs meet, and the total is as small as it gets | |
Neither extreme is where the total is smallest. The best is the one where the two terms are of comparable size, because on either side of that point every saving in one job is paid for by the other.
Locating that point is awkward with the notation we have, because neither term is polynomial in the input length nor exponential in it. Costs in that gap are usually written in L-notation, as , and only two things about it matter here: the exponent says where in the gap a cost falls, running from polynomial at to exponential at , and the constant refines the estimate within a scale.
Now measure both costs on that scale. Suppose the values that must be smooth have size , and choose a factor base . An -value is an exponential, so taking logarithms leaves and as products of powers of and , and in their ratio the exponents subtract:
That subtraction drives the rest. Since , the search cost has an exponent proportional to , which is exactly the shape of . The leading factor contributes only , no larger than the search term at the balance point we are heading for, so it leaves the scale alone. On the other side, squaring doubles a constant but does not touch the exponent, so the linear algebra stays at . The mapping worth remembering is that the size of the numbers being smoothed contributes , the size of the factor base contributes , and the search pays the difference between them:
A sum of two -terms is set by the larger exponent; the smaller one is swallowed by the slack the notation already carries. So if , the cost is relation collection and the matrix was free; if , the cost is linear algebra and the relations were free. From either side, moving toward the other case lowers the total, until the two exponents meet:
Once is known, the best factor base is the one that splits that exponent evenly between the two jobs. Nothing in the argument is specific to GNFS: it holds for any method that collects smooth relations and then solves for a dependency among them.
Take the quadratic sieve first. It smooths values of , which are about as large as itself, and , so . Balancing gives , and a running time of .
GNFS changes one thing about that calculation: the values it tests are not of size . With the degree chosen as , the pair of values and that must both be smooth are heuristically of size , so . The same balancing gives :
The distance between and is the whole of the improvement, and it is worth being exact about where it comes from. GNFS does not test smoothness any faster than the quadratic sieve does. It wins because its polynomial construction hands it much smaller numbers to make smooth. That lowers , and every exponent in the analysis is downstream of .
What the balancing argument gives is the shape of the complexity: which power of appears, and why it is rather than . The constant in front takes a longer optimization, one that tunes the degree and the smoothness bound together rather than one after the other, since is what sets the size of the values and therefore the rate at which they are smooth. It selects
Squaring doubles its constant, and is : the familiar constant arrives out of the linear algebra. Relation collection is tuned to cost the same — the balancing argument again, this time with the constants kept — so the total carries that constant too:
In terms of bits, with , we have and , so the exponent is and
Read that exponent both ways. It grows with , so the cost is not polynomial in the input length. But it grows like rather than like , which leaves it far below the of trial division. Between the two is what subexponential means, and it is where the best factoring algorithms known today live.
So the fastest known way to factor large integers today is GNFS, with a cost of . There might be a faster classical algorithm: no polynomial-time method is known, but factoring has never been shown to be NP-complete either, so as of today this has been neither proved nor disproved. But a faster quantum algorithm is already known—we come to it later.
Classical circuits as quantum circuits
Classical and quantum computation have been treated separately so far. In practice, quantum algorithms routinely need ordinary classical computation inside a larger quantum circuit: adding two integers, evaluating a function, checking a condition. So can a classical algorithm be run on a quantum computer?
Yes. Any Boolean circuit of size can be implemented with quantum gates.
The purpose is compatibility rather than speed. A classical computation run this way is no faster than before, but it now runs coherently: it behaves correctly when its input is part of a superposition, and it leaves its output in a register the rest of the quantum algorithm can use.
Toffoli gates
Classical gates such as AND and OR destroy information. AND takes two input bits and returns one, so its four possible inputs collapse onto two possible outputs: a at the output could have come from any of , or , and there is no way to tell which. That is the one obstacle here, because every quantum gate is unitary and therefore reversible. A Boolean circuit has to be rebuilt out of reversible gates before a quantum computer can run it, and the gate that does that work is the Toffoli gate.
Recall that a is a controlled-controlled-NOT: it flips its target qubit only when both control qubits are .
| in | out | |||||
|---|---|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 0 | 0 | 1 | 0 | 0 | 0 | 1 |
| 0 | 1 | 0 | 0 | 0 | 1 | 0 |
| 0 | 1 | 1 | 0 | 0 | 1 | 1 |
| 1 | 0 | 0 | 0 | 1 | 0 | 0 |
| 1 | 0 | 1 | 0 | 1 | 0 | 1 |
| 1 | 1 | 0 | 1 | 1 | 1 | 1 |
| 1 | 1 | 1 | 1 | 1 | 1 | 0 |
Toffoli from elementary gates
The has no three-qubit gate, so one Toffoli gate has to be built from several elementary gates. The circuit below uses 15 elementary gates: two Hadamards, six CNOTs, and seven or gates. The decomposition is exact — these 15 gates reproduce the Toffoli operation exactly, not approximately.
This illustrates the main cost of translating classical computation into quantum computation. A single classical operation such as AND can correspond to a whole collection of elementary quantum gates. But the number of gates needed is a fixed constant: one Toffoli costs 15 elementary gates, or simply . So a classical circuit with gates can still be implemented with elementary quantum gates. The translation introduces overhead, but only a constant-factor overhead.
Simulating Boolean gates
Now that we can build a Toffoli gate from elementary quantum gates, we can use it to reproduce . The key idea is simple: because quantum gates must be reversible, a Boolean operation is computed into an additional qubit rather than replacing its inputs. With the target initialized to , the quantum circuit can therefore reproduce the same Boolean function on computational-basis states.
NOT
Nothing to do: NOT is already reversible, and the Pauli-X gate implements exactly the same operation on the two basis states.
FANOUT
A CNOT with a fresh qubit as its target implements FANOUT on basis states: it copies the input bit to the fresh qubit. This does not violate the no-cloning theorem, because it does not copy an arbitrary quantum state.
AND
A Toffoli gate with a fresh target qubit computes into it: starting from , the target ends as , which is exactly for bits .
OR
By De Morgan’s law an OR is an AND with everything flipped: flip both inputs, AND them with a Toffoli, then flip the result. The two inputs are left flipped on the way out.
So every Boolean gate can be replaced by quantum gates, using at most one workspace qubit initialized to . A Boolean circuit with gates therefore becomes a quantum circuit with gates and qubits.
But there is a catch: the quantum version is reversible, so it cannot simply discard the inputs or intermediate values the way a classical circuit does. Instead, they remain in the circuit, leaving behind workspace that must eventually be cleaned up.
Simulating Boolean circuits
Now take a whole circuit rather than one gate. Suppose is a Boolean circuit of size computing a function :
Replace each Boolean gate by its quantum simulation, adding a fresh qubit whenever needed. The resulting quantum circuit uses gates and acts on qubits, where the workspace . For a basis-state input , the desired -bit output appears in the first qubits, but the remaining qubits contain leftover intermediate values:
Here is the garbage produced by making the computation reversible.
Clearing the garbage
The garbage is more than wasted space: if it remains entangled with the result, it can interfere with the quantum algorithm and spoil the interference patterns we rely on. The simple solution is to uncompute it. Because is made entirely of reversible quantum gates, we can run it backwards using its inverse , at the same cost. This lets us compute the result, use it where needed, and then erase the unwanted intermediate values without erasing the result itself.
The key is that is deterministic: once we have computed , we can copy that classical result before undoing the computation. We therefore add a fresh -qubit register , initially , and use CNOTs to copy the answer into it between and . This is the same FANOUT trick as before: the result wires hold basis-state bits, so copying them does not violate the no-cloning theorem. Then erases the workspace while leaving the copied result untouched.
Constructing the query gate
Combine the three circuit segments — the computation of , the XOR of into the target register, and the uncomputation of the workspace — and call the resulting circuit . Its cost is
since the computation and uncomputation each cost , while the -gate target update is absorbed into .
More importantly, the workspace register is returned to after the uncomputation. Thus the complete circuit acts as
Because the workspace starts and ends in the fixed state , it can be ignored when describing the action of the circuit on the input and target registers. The remaining transformation is exactly the quantum query gate for the function computed by the original Boolean circuit.
In other words, the query-model oracle does not have to be treated as an abstract black box: given a classical circuit for , we can construct its quantum query gate using gates, only a constant-factor overhead compared with the original circuit.
Phase estimation and factoring
A quantum state can sometimes pick up a phase when a unitary operation is applied to it. That phase is , but it contains useful information about the operation. Phase estimation is a procedure for extracting that hidden phase.
The spectral theorem
A useful way to understand a matrix is to look for directions that it does not mix with other directions. These are its eigenvectors: if , then applying to does not turn into a different direction, it only multiplies it by the number .
- Eigenvector with eigenvalue . It keeps its own line.
- Eigenvector with eigenvalue . It keeps its own line.
- Any other direction is not an eigenvector: drag the slider and it leaves its dashed line.
For a general matrix, there may not be enough eigenvectors to form a basis. And even when there are enough, they need not be perpendicular to one another. Either way, they are not necessarily convenient as coordinates for the whole space.
The spectral theorem identifies a class of matrices whose eigenvectors can be chosen to form an . This gives us a particularly useful coordinate system: the matrix acts on each direction independently, multiplying it by that direction’s own eigenvalue.
- and stay on their own lines. Their eigenvalues only change their lengths.
- Any other vector has components along both eigendirections. Since those components are stretched by different amounts, the vector changes direction as well as length.
- The dashed circle represents all unit vectors. Under , these vectors map to the solid ellipse, whose axes lie along the two eigendirections.
The eigenvalues here are real, so they stretch or shrink the eigenvector directions. A unitary matrix preserves lengths, so its eigenvalues have magnitude 1: in the complex plane, they rotate each direction by a phase instead of changing its length. That phase is what this chapter is after — and it is the one part a real two-dimensional picture cannot show.
The spectral decomposition
A matrix is normal when it commutes with its :
The spectral theorem says that every normal matrix has an orthonormal basis of eigenvectors , together with phases , with corresponding complex eigenvalues , such that
Each basis vector satisfies
Writing a matrix in this form is called its spectral decomposition. It says that the entire matrix is determined by an orthonormal set of directions and one complex number for each direction, specifying what does along it.
Special case: unitary matrices
A unitary matrix satisfies , so it is normal and the spectral theorem applies. What unitarity adds is a constraint on the eigenvalues. A unitary operation preserves norms, so if , then the output must have the same length as the input. This forces .
A complex number of modulus one does not change a vector’s length. It only contributes a phase: a rotation in the complex plane. Every such number can be written as for exactly one .
So suppose is an unitary matrix. There exists an orthonormal basis , together with phases
such that
Each vector is an eigenvector of with eigenvalue :
For a unitary matrix, the spectral decomposition therefore reduces the action of the entire matrix to a collection of phases. Each eigenvector defines an independent direction, and along that direction the matrix does nothing more than multiply by . The magnitude is fixed at one, so the only information left in each eigenvalue is its phase .
The phase estimation problem
In the phase estimation problem, we are given two things:
- A description of a quantum circuit on qubits implementing a unitary operation .
- An -qubit quantum state .
We are promised that is an eigenvector of . By the spectral theorem, its eigenvalue has the form for a unique . The goal is to approximate this phase , where
The important point is that the eigenvector is given as a quantum state, not as a classical description. We cannot simply read from the circuit, nor can we measure to reveal which eigenvector it is. The phase must be extracted by interacting with the state through controlled applications of .
The phase estimate
The phase is a real number, but a quantum measurement can return only finitely many classical bits. We therefore choose a precision : the algorithm will return bits that specify one of possible approximations to .
For example, with , the possible answers are the eight equally spaced points .
If the true phase is , the closest grid point is , so the three-bit answer is , representing the approximation . In general, the answer has the form for , and the binary representation of is the -bit output.
There is one important detail: these points lie on a circle, not on a line. The phases and represent the same point, because . So the approximation is understood modulo one. A phase close to can therefore be approximated by a value close to when the shortest distance around the circle crosses the boundary.
Phase kickback: making the phase observable
Applying to multiplies the state by and changes nothing else, so measuring the resulting state cannot reveal . Phase kickback turns this invisible phase into an observable relative phase: instead of applying directly, we apply it conditionally on an extra qubit, transferring the phase to the control qubit.
Creating an observable phase
A controlled- uses an extra qubit to decide whether is applied: one branch does nothing, while the other applies to the register. If the control is in a definite state or this does not help, because only one branch ever exists and the phase remains global.
The key is to put the control into a superposition. Both branches are then present at once: one where is applied and one where it is not. Since is an eigenvector, it picks up and nothing else, and only in the branch where acts, so the phase becomes a relative phase between the two branches. A second Hadamard makes those branches interfere, converting the relative phase into measurement probabilities on the control qubit. The register itself is never measured. Everything we learn about comes from the control.
Step through the circuit
- 1Prepare the register in and the control qubit in .
- 2Apply a Hadamard to the control qubit.
- 3Apply controlled-.
- 4Apply a Hadamard to the control qubit again.
- 5Measure the control qubit. The register is never measured.
What can we learn from one measurement?
The measurement does tell us something about : the probabilities change as the phase changes. For example, phases near tend to produce , while phases near tend to produce .
But this is not enough to determine the phase. The same measurement statistics can arise from different phases: and are indistinguishable. The probabilities also change very little near and , so this measurement gives poor precision there.
So one controlled- lets us learn something about the phase, but not enough to identify it. To estimate accurately, we need a way to make the measurement more sensitive to different parts of the phase.
Running controlled-U twice
The first experiment was not sensitive enough to distinguish all phases. A natural idea is therefore to apply more than once. If one application gives the phase , then two applications give twice the phase:
So if we put two controlled- gates on the same control qubit, we get the same experiment as before, but with the phase doubled. This changes how the measurement probabilities respond to , giving us information that the single- experiment could not provide.
More sensitivity, more ambiguity
Doubling the phase makes the probabilities change twice as quickly as changes. Phases that were hard to distinguish before can now produce noticeably different probabilities, so the measurement becomes more sensitive to the phase.
But the doubled phase is still read modulo one. In particular, and represent the same phase, so and produce identical statistics. The original reflection symmetry, , remains as well. We have therefore gained sensitivity, but also introduced more possible phases that give the same measurement statistics.
This is the central tension in phase estimation: using more applications of gives finer information about the phase, but also creates more ambiguity about which phase produced it. The solution will be to use several powers of together, so that the ambiguities from one measurement are resolved by the others.
What do we gain by using both experiments?
We now have two experiments with complementary strengths. One application of covers the whole range of , but resolves it coarsely. Two applications make the probabilities change twice as quickly, but introduce additional ambiguities. It is natural to ask whether the information from the two experiments can be put together to get a better estimate.
The register itself is not the obstacle. Because is an eigenvector, each experiment leaves it unchanged and separates it from the control qubit. Measuring the control therefore does not disturb , so the experiment can be repeated with the same state.
The difficulty is that measurement throws away most of the information available before measurement. Just before measurement, the control qubit has amplitudes whose relative phase depends on . Measurement turns those amplitudes into a single classical bit, or . To learn the corresponding probabilities accurately, we need many repetitions.
So if we run the and experiments separately, we end up with two collections of classical measurement results. We can estimate two probabilities and try to use them together, but each estimate is noisy and each experiment has its own ambiguities.
This raises the next question: can we arrange the experiments so that their phase information is combined before measurement, rather than after?
Two control qubits
Rather than running the two experiments one after another, we can give each of them its own control qubit and run them in a single circuit. The upper control drives one application of , and the lower control drives two.
Step through the circuit
- 1Prepare the register in and both control qubits in .
- 2Apply a Hadamard to each control qubit.
- 3Apply controlled- once, controlled by .
- 4Apply controlled- twice, both controlled by .
Can we distinguish the phases?
The two controls now carry the control factor of : .
In general, need not be restricted to a few special values. But to make the problem concrete, let us first pretend that we are promised for some . This gives us a smaller problem: can we work out which of these four possible values of we have?
Each possibility gives a different two-qubit state: . Explicitly,
Our goal is now clear: determine which of the four states the controls are in. If we can identify the state, we immediately know , and therefore the original phase . And conveniently, notice that all four states are , so they can be distinguished perfectly by a : .
Knowing that the four states can be distinguished does not yet give us a way to read out which one we have. We need to change the basis back to the computational basis. Let be the unitary whose columns are , , , and . By construction, for every . In this case,
This matrix is the in four dimensions. As a quantum operation, it is called the quantum Fourier transform, or .
Now apply the inverse transformation. It takes each of our four states back to the corresponding computational-basis state: .
So instead of building a special measurement for the four states, we can simply apply and then measure the qubits in the computational basis. The measurement gives us , and therefore the phase .
At the four promised phases, each curve reaches exactly at its own quarter and at the others, so the measurement is certain. Between those phases, the peaks spread out: the outcome is no longer certain, but the nearest quarter remains the most likely.
The quantum Fourier transform
The key idea is to build states whose amplitudes all have the same magnitude but differ in phase.
For example, suppose there are four computational-basis states, labelled . The phase can stay constant, or advance by a quarter, half, or three quarters of a full turn each time increases.
Complex phase
rows are the frequency y, columns the position x | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
| 0 | ||||
| 1 | ||||
| 2 | ||||
| 3 |
As increases, the phase can advance at different rates. Each rate produces a different pattern, corresponding to a different discrete frequency.
The quantum Fourier transform is the change of basis from the computational-basis states to these frequency patterns. It is the quantum counterpart of the , with the normalization factor that makes the frequency patterns orthonormal and the transformation unitary.
For a positive integer , the quantum Fourier transform is the unitary defined by
Equivalently, its action on a computational-basis state is
The second form is often easier to read. Start with the basis state . The transform produces a superposition of all the output basis states . Every output basis state has the same amplitude magnitude, . What changes with is the phase .
The phase factor is determined by the product . For a fixed input , increasing makes the phase advance in equal steps, and the value of determines how large those steps are. For example, gives no phase change. advances by one step around the circle — a quarter-turn in the four-state example above. advances twice as far at each step, and so on. Each input basis state is therefore mapped to a different phase pattern.
For an -qubit register, , because that is the number of computational-basis states available. The definition itself does not require to be a power of two — that restriction comes from applying the transform to a register of whole qubits.
Examples at different sizes
Since , only matters. So, no matter how large becomes, the entries use only distinct phases, for . Let’s look at a few examples, starting with the smallest transform.
There is one basis state and one phase: .
Shorthand notation for phase
The same phases keep appearing in every transform. Instead of writing the exponential each time, name the first phase: . Then every phase is a power of it: .
On the unit circle, is one step of . Its powers take successive steps around the circle: . The distinct powers are the .
A column of the transform follows the same walk. Fixing , its exponents are , so each row advances by steps around the circle.
Powers of ω
Where the arrow lands is a pair of coordinates, written down by Euler’s formula: .
So naming collapses the definition to a sum of its powers, and the matrix to a table of them:
Turning phase back into a number
Undoing the transform conjugates every phase, so the inverse is the same matrix with the sign of the exponent reversed:
This is the direction used in phase estimation. The controlled- gates leave the control register in one of the phase patterns above — a Fourier-basis state, not a computational-basis state. That is why measuring the controls directly tells us so little.
maps that phase pattern back to the computational basis: . After that, an ordinary measurement reveals .
Circuits for the QFT
When , the QFT acts on qubits. Its phase pattern has a simple, repeating structure that we can use: each qubit contributes one level of the pattern, with smaller phase rotations appearing as we move along the qubits. This lets us build the QFT efficiently as a ladder of single-qubit gates and controlled phase rotations, rather than treating every basis state separately.
For a computational-basis input , the output can be written as a tensor product of single-qubit states:
The tensor-product symbol means that we combine these single-qubit states into the full -qubit state. Every factor has the same form, , where is the phase for that qubit. The term carries no explicit phase because , so it is the phase reference. The term carries the relative phase .
So each output qubit is an equal superposition of and , with a phase that depends on and on which qubit we are looking at. The phases differ by powers of two, giving the QFT its characteristic phase pattern.
Building blocks
The output qubits are not entangled with one another, so we can build the state one qubit at a time.
The Hadamard gate creates the equal superposition , which is the basic form of each single-qubit factor above.
A controlled-phase gate adds a phase only to the state:
The gate is symmetric: it does not matter which qubit is considered the control and which is the target. Both qubits simply need to be for the phase to be applied. This is why its circuit symbol has two identical dots rather than a separate control and target.
The circuit pattern
The circuit is built from one short pattern repeated across the wires. Each wire gets a Hadamard followed by controlled-phase gates connecting it to the wires below. The phase angles decrease by powers of two: the largest angle, , connects the wire being worked on to the bottom wire, then , , and so on as the connections move upward.
The resulting phase factors appear on the output wires in reverse order. The final swaps reverse the wire order and put them back into the intended positions.
In the picture, the part of the circuit not yet drawn out is folded into a single box on the left. Unfolding that box reveals another copy of the same pattern.
Cost analysis
Let denote the number of gates we need for qubits. For , a single Hadamard gate is required. For , these are the gates required:
- gates for the QFT on qubits
- controlled-phase gates
- swap gates
- 1 Hadamard gate
This is a recurrence relation with a :
So cost is gates for a transform on amplitudes — quadratic in the number of qubits, for a matrix with entries in it.
The swap gates can be reduced. Taken together, they simply reverse the order of the wires, so we need only swaps if we perform that reversal directly. We can also omit them entirely if we are willing to relabel the wires.
The QFT can also be approximated with fewer gates and lower depth. Its phase angles shrink geometrically: , , , and so on. Once the rotations become small enough, dropping them has little effect while reducing the cost of the circuit.
The inverse QFT
Phase estimation runs this circuit backwards. Reversing the order of the gates and changing every phase angle to gives at the same cost.
This is the circuit that turns the phase pattern left behind by the controlled- gates back into the computational basis, where a measurement can read the encoded number.
Phase estimation with control qubits
The two-control circuit generalises to control qubits without changing its basic shape. Each control applies a different power of , so the control register accumulates a phase pattern determined by . With controls, this pattern contains bits of phase information. It has exactly the form produced by from the corresponding basis state, so we apply and measure the controls to recover those bits.
The eigenstate is unchanged by every controlled power of , because is an eigenvector of and therefore of every power of it. All the phase information is stored in the control register. Just before measurement, the full state is
So the probability of reading is
Accuracy of a single run
The probability of measuring the control register in depends only on the distance between and the corresponding grid point . If , every term in the sum is , so . Otherwise the terms do not line up perfectly, and is smaller.
The possible estimates are spaced by . The nearest grid point is therefore at most half a step from , . For phase differences this small, the probability formula above gives .
Conversely, if a grid point is at least one full step from , , the same probability formula gives .
Thus the nearest grid point has at least a chance of appearing in one run, while any grid point at least one full step away has probability at most .
A single run therefore favors the best approximation but does not guarantee it. Repeating the procedure and taking the mode of the outcomes makes that approximation increasingly likely. The eigenvector is unchanged, so it can be reused for every run.
Alternative phase-estimation methods
Standard phase estimation estimates the phase using controlled applications of . Other approaches use different combinations of quantum resources and classical processing:
- Iterative phase estimation extracts the phase bits one at a time, reusing a single control qubit instead of keeping control qubits at once.
- Kitaev’s phase estimation uses a single control qubit and estimates the phase from interference measurements involving different powers of .
- Maximum-likelihood and Bayesian methods repeat controlled- experiments and use classical statistical inference to estimate .
These approaches trade off the same basic resources: control qubits, applications of , and classical post-processing.
The order-finding problem: using phase estimation
When working modulo , we only need possible values, represented by the integers from to . We denote this set by . Thus , , , and so on.
The elements that satisfy have an important property: they have a multiplicative inverse modulo . We collect all of them into the set . For , for example, twelve of the twenty-one elements are invertible: .
The connection with the greatest common divisor follows from the Euclidean algorithm. If , it gives integers and such that . Reducing modulo gives , so is a multiplicative inverse of . Conversely, if has an inverse modulo , then must be .
Now take any and repeatedly multiply by , producing the powers Every one of them is invertible too: if is the inverse of , then is the inverse of . So all the powers lie in , and that set is finite, so they cannot all be different. Two of them must be equal: for some . Multiplying both sides by the inverse of cancels it and leaves , where is positive. So some positive power of returns to .
So, the smallest positive exponent for which is called the order of in .
For elements outside no such exponent exists: if , then divides both and , so would force to divide , which is impossible.
Powers of modulo
The problem
We are given two positive integers and , with the promise that . The task is to find the order of : the smallest positive integer such that . The two numbers and are all we are given. In particular, no factorization of is provided.
Both numbers are written in binary, so the input length is bits. Computing a single power is efficient: does it using gates. The difficulty is that the order can be almost as large as . Checking the powers one at a time can therefore require steps, which is exponential in the input length .
The table below runs that scan for . Each modulus is about ten times the one above it, and so is the time.
| order | time | |
|---|---|---|
| 9,610,721 | — | — |
| 40,670,489 | — | — |
| 207,335,717 | — | — |
| 4,043,918,803 | — | — |
Scan to measure multiplication speed and estimate the cost at different sizes.
No efficient classical algorithm for order-finding is known. This is significant because order-finding is closely related to integer factorization. In fact, an efficient order-finding algorithm can be used to efficiently, so factorization can be reduced to order-finding.
Multiplication as a unitary operation
We know what we want to find: the length of the cycle that repeated multiplication by modulo runs through. The idea is to turn that repeated multiplication into an operation a quantum computer can apply to a state. For a given element , define the operation as for each .
Because has a multiplicative inverse modulo , multiplication by is a bijection on : every state has exactly one image, and every state has exactly one preimage. In other words, multiplication by simply permutes the elements of .
A permutation of the computational basis states is represented by a unitary matrix. This is why is a valid quantum operation.
If , this breaks down. Every product is divisible by , so the map can reach only a subset of the states. Multiple inputs therefore collide at the same output, while other states are never reached. The map is no longer a permutation, and its matrix is not unitary.
A permutation can be decomposed into cycles: starting from any state, repeatedly applying eventually returns to that state. For multiplication by , these cycles are determined by the repeated powers of modulo .
For example, take and . The state remains fixed, while starting from , repeated application of gives . The cycle therefore has length . Equivalently, , and no smaller positive power gives , so the order of modulo is .
The remaining states form cycles of their own: and , while is fixed. Together, these cycles make up the full permutation implemented by .
This is the key connection: the order we want is encoded as the length of a cycle in the permutation . The remaining challenge is to extract that cycle length from the unitary using quantum phase estimation.
From the cycle to eigenvalues
At this point the order is hidden as the number of positions in a cycle. Phase estimation does not measure that cycle length directly. It measures an eigenphase, so the goal is to encode the cycle length into an eigenphase of the form .
The cycle containing consists of the states . On this part of the state space, has one simple action: move everything one position forward, wrapping the last position back to the first:
A basis state does not have the property we need. For example, , so applying changes it into a different basis state. Instead, consider a superposition of the states in the cycle. With the right pattern of phases, the shift preserves this superposition and changes only its overall phase. Such a state is an eigenvector, and the corresponding phase change is its eigenvalue.
Begin with , the equal superposition of all positions in the cycle, with every amplitude having the same phase:
Applying moves every term one position forward. The last state wraps back to , so the same terms appear again, only in a different order. The state is therefore unchanged: its eigenvalue is , corresponding to eigenphase . This is a valid eigenvector, but its phase contains no information about .
We need eigenvectors with nonzero eigenphases. The simplest way to get one is to let the amplitudes acquire a phase difference from one position to the next. Because the cycle contains positions, this phase difference must fit consistently when the cycle closes: after steps, the phase must return to its starting value. A natural choice is therefore of a full turn per step. Writing this phase step as , we have .
Now look at . We assign successive positions phases that differ by of a turn, so position carries the factor (the minus sign is a convention):
Applying shifts every position forward by one step. The phase pattern shifts with the states, and when the last term wraps back to , its phase factor becomes . Rearranging the terms shows that every amplitude has acquired the same extra factor . The phase pattern is therefore unchanged, while the whole state gains the eigenphase .
By the same logic, we can choose different phase steps to obtain a whole family of eigenvectors. The state is an equal superposition of all basis states in the cycle through , with only their phases differing. Each component has magnitude . The label determines the phase difference between neighbouring positions: the phase advances by of a turn from one position to the next. Thus, the component on carries the phase factor :
Every state in this family is an eigenvector of , with eigenvalue .
Note that there are different ways to choose the phase pattern and construct eigenvectors. For this problem, however, these particular eigenvectors are useful because their eigenphases are , so the unknown cycle length appears directly in the denominator.
The phase pattern of an eigenstate
The phase pattern is what makes these states useful for phase estimation. Under every controlled power of , an eigenvector remains the same target state while its phase accumulates in the control register.
From eigenphase to order
Among the eigenvectors above, start with . Its eigenphase is , which carries no information about the unknown order . The next choice, , is exactly what we need: its eigenphase is , putting the unknown order directly in the denominator:
This gives us a direct route from phase estimation to the order. If we can prepare , phase estimation gives an estimate of its eigenphase, which in this case is . We can then invert that estimate to obtain .
- Perform phase estimation on using a quantum circuit implementing , with control qubits. The controlled powers of accumulate the phase in the control register. The inverse QFT converts this accumulated phase into an estimate of the eigenphase. Measuring the control register gives an integer . Dividing by turns that -bit readout into a phase estimate in . And since the eigenphase is , .
- Recover the order by inverting the phase estimate and rounding it to the nearest integer: .
How accurate does the phase estimate need to be?
The estimate of must be accurate enough to distinguish it from the phase corresponding to any other possible order . Since both and are smaller than , the smallest possible separation between two such phases is .
Therefore, if the phase estimate is within half of this minimum separation from the true phase, it cannot be mistaken for the phase of a different possible order. In other words, it is enough to have .
With control qubits, the phase-estimation grid has spacing , so the nearest grid point is at most away from the true phase. Choosing makes this error at most , comfortably within the required precision. Thus control qubits are enough.
A single run produces the nearest grid point with probability at least , about 40%. Repeating the procedure independently increases the probability of obtaining the correct phase. After runs, the probability that at least one run produces the nearest grid point is at least , so a constant number of repetitions gives any fixed desired success probability, while repetitions give failure probability at most .
So, we choose enough qubits so that the useful region around the true phase is narrow enough to identify . And adding more qubits makes the grid finer and the phase estimate more precise, while repetitions can further boost the probability of obtaining a sufficiently accurate estimate.
When the eigenphase is a random fraction
The previous procedure assumed that we could start with , whose eigenphase is . But there is nothing special about : suppose instead that we are given for a random choice of . Its eigenphase is , so phase estimation now returns that fraction rather than :
We can estimate as follows:
- Perform phase estimation on the state using a quantum circuit implementing , with control qubits. The outcome is an integer such that approximates .
- Find the fraction in lowest terms, with and , that is closest to . The continued fraction algorithm finds this fraction efficiently.
The same precision bound is enough. Two distinct fractions with denominators below are more than apart, so an estimate within half that gap identifies uniquely:
Thus the same choice makes the correct fraction likely to be recovered.
There is one complication: continued fractions return the fraction in lowest terms. Suppose, for example, that the true eigenphase is . The algorithm sees only the value , so it returns rather than . In general, if and share a common factor, the denominator returned is only , a proper divisor of . A single run therefore may not reveal the order.
Repeating the procedure solves this problem. Each run gives a denominator for an independently chosen . Taking the least common multiple of the denominators observed across several runs recovers with high probability.
The continued fraction algorithm
At this point, phase estimation has given us an integer measurement outcome . We turn it into a number in by dividing by : . The value is our estimate of the eigenphase . The denominator is determined entirely by the number of control qubits, so it tells us nothing about the unknown order .
What we want is a fraction that is close to , with a denominator . This bound comes from the problem itself: the order satisfies . If the phase estimate satisfies , then is close enough to the true eigenphase that this reduced fraction is uniquely determined among fractions with denominators below .
This is where continued fractions enter. Starting from , the continued fraction algorithm repeatedly divides with remainder. These divisions produce a sequence of integers called the continued-fraction terms. From these terms we construct fractions called the convergents. Each convergent is a rational approximation to . As we move through the sequence, the approximations become better while their denominators grow.
| Euclidean division | term | test | ||
|---|---|---|---|---|
| kept | ||||
| stop |
phase estimate
recovered fraction
distance
The state we can prepare
So far, the procedure was described as if we had to start with a particular eigenvector such as . But preparing , or any other , would require knowing the order in advance — exactly what we are trying to find.
Fortunately, we can start with a state we already know how to prepare: . On the cycle containing , this basis state is an equal superposition of all eigenvectors: .
To see this, substitute the definition of : .
For , every phase factor is , so the sum over gives . For every , the factors run through all th roots of unity and sum to zero. All terms with therefore cancel, leaving only the term: .
This is exactly what we need. Starting with means that phase estimation runs simultaneously on all the eigenvectors . Each one contributes its own eigenphase , and the measurement selects one of these phases.
The important point is that we do not need to know which was selected. Whatever phase we obtain has the form , so the continued fraction step can recover its reduced denominator. Repeating the procedure with fresh copies of gives several such denominators, whose least common multiple reveals the unknown order with high probability.
Implementation
Every piece is now in place. We know a state we can prepare, , and an operation whose eigenphases are the fractions . We also know how to read one of those fractions off the control register. Putting them together gives the circuit that finds the order of .
What does one run cost? Write for the number of bits of . The control register holds qubits, so the circuit opens with Hadamard gates and closes with an inverse Fourier transform over , which costs gates.
The controlled unitaries are the expensive part, and they are cheaper than they look. Nothing forces us to apply repeatedly: both and are known in advance, so each power for can be worked out classically by before the circuit is built. What the circuit runs is then a single multiplication , at cost . With of them, the controlled unitaries cost , and that dominates the total: the whole circuit runs in gates.
This is the payoff of the whole construction. Searching for the order classically means walking through the powers of one at a time, and the order can be almost as large as , so the walk can run to steps — exponential in the input length. The circuit above answers the same question with a number of gates that grows like .
Factoring through order-finding
Order-finding may seem far removed from factoring: it tells us about the exponents that make powers of repeat, not about the divisors of . The key idea is that this periodicity contains exactly the information we need. From the order of a suitable modulo , a few lines of classical arithmetic can reveal a non-trivial factor of .
The reduction works under a few conditions. We take to be odd and composite, and choose so that . For such an , the standard analysis guarantees that a randomly chosen produces useful factors with probability at least . If an attempt fails, we simply choose another and repeat.
So, before running order-finding, we deal with the easy cases classically. If is even, we immediately have the factor . If is prime, there is nothing to factor. Classical Miller–Rabin and AKS primality tests can detect this efficiently. And if is a perfect power , taking successive roots hands us directly. What is left is an odd composite that is not a prime power, and that is the only case the quantum procedure is needed for.
How a repeating power reveals a factor
Suppose the order we get back is even. Then is a whole number, so we may halve the exponent and set . Squaring puts the exponent back to , and by definition of the order. So the halved power is a square root of modulo :
The last step is where the factor comes from. Saying that squares to is the same as saying that divides , and a difference of squares splits that quantity into the two brackets and . So divides a product of two numbers that differ by only — and that is a sharp constraint on where the prime factors of can be hiding.
Because is odd, no prime of can divide two numbers that differ by , so each prime power making up has to sit entirely in one bracket or the other. If they all sit in the same bracket, that bracket is a multiple of and we learn nothing. But if they are shared between the two, then picks up precisely the parts on the left and precisely the parts on the right. Both are proper factors of , and Euclid’s algorithm produces them in a moment.
Putting it all together
We now have all the pieces of Shor’s algorithm. The full run makes one thing especially clear: almost all of the work is classical. Choosing , checking the conditions, , and are all classical operations. The only quantum step is finding the order — the crucial part that makes the whole approach useful.
- 1Draw at random froma = 4
- 2Take
- quantum step 3Find the order : the least with
- 4Check the parity of
- 5Halve the exponent:
- 6Take and
Candidates for a
Grover's algorithm
Unstructured search
Let denote the binary alphabet. Suppose we are given a function we can compute efficiently, , and our goal is to find a solution: a binary string for which .
This is unstructured search because is arbitrary. There is no promise attached to it, so there is no structure to exploit—no ordering, periodicity, or gradient to follow. Learning that for one string rules out that string but tells us nothing about any other.
A PIN that opens a lock is easy to check, but a failed attempt gives no clue about the next one. The same pattern appears whenever we have a cheap way to test a candidate but no useful information about where to look next. In every case, is the cheap checker, and Search asks us to find something it accepts.
Hereafter, let denote the number of strings in , so that we can express costs in terms of the size of the search space rather than the number of bits. It is also useful to name the two sets into which the strings are divided: and . Let be the number of solutions. Search asks us to produce an element of , while Unique search is the special case .
By iterating through all and evaluating on each one, we can solve Search with queries, and no deterministic algorithm can guarantee a solution with fewer. Probabilistic algorithms can do slightly better on average by stopping as soon as a solution is found, but they still require a number of queries that is linear in .
Search by hand
Grover’s algorithm is a quantum algorithm for Search requiring queries. Compared with Shor’s exponential speedup, a quadratic saving sounds modest, and it is. Whether it offers a practical advantage is a separate question. But Grover is still important: it applies to completely unstructured search, with no promise or hidden structure, and its quadratic speedup is the largest possible in the query model.
Phase query gates
So far, queries have been made through the , which writes the answer into a workspace qubit: .
Grover’s algorithm is easier to describe using a second form of query, which records the answer as a phase rather than in a qubit. For a function , the phase query gate is the -qubit operation defined by for every .
This is the first of the two phase gates Grover’s algorithm needs: it marks the solutions by reversing their sign, and leaves every non-solution exactly as it was. A measurement cannot see that mark directly—a sign is not a probability—which is why the rest of the algorithm is needed. A single query marks every solution at once, and Grover’s algorithm is the machinery that turns those marks into amplitude a measurement can find.
Each gate from the other
The phase query is not a different oracle. It is the same query used with the workspace qubit prepared in . In that case, the workspace qubit returns to , while the value of appears as a phase on (phase kickback): .
The construction runs in the other direction too, so an algorithm counted in queries and one counted in queries are counted on the same scale.
The second phase gate is not a query to the problem’s function . It is a fixed operation that we can build directly into the circuit, based on the simple, known function defined by
Its phase query gate is
Unlike , which queries the unknown , is a fixed, known operation that does not depend on the search problem. Its circuit can be built once and for all as an -fold controlled- gate with gates before and after it. It provides the fixed reflection used in each Grover iteration, adding gates but no queries. Thus, only counts toward the query count.
Grover’s algorithm
Grover’s algorithm repeatedly applies one fixed Grover operation:
Each application consists of a phase query , followed by a fixed sequence of gates that amplifies the amplitudes of the solutions. Only depends on the unknown function and therefore counts as a query, so with the other three gates fixed, iterations use exactly queries.
The operation is applied to the uniform superposition, where :
Before any amplification, every string has the same probability of being measured. If there are solutions, a measurement finds one with probability —the quantum equivalent of one blind guess.
Grover’s algorithm uses the repeated application of to move probability amplitude from non-solutions to solutions. After the right number of iterations, no more and no less, measuring the register is much more likely to produce a solution. The walkthrough below runs the circuit one stage at a time, with the state after each stage and the picture that goes with it.
Step through the circuit
- 1Prepare. Start the qubits in and apply a Hadamard to each, producing the uniform superposition .
- 2Iterate. Apply the Grover operation exactly times.
- 3Measure. Measure all qubits in the standard basis and return the resulting string. One classical evaluation of checks whether it is a solution.
Cost analysis
Two quantities determine the cost of Grover’s algorithm: the number of iterations and the success probability after those iterations. For solutions among possible strings, the optimal iteration count is approximately , with success probability close to when the solutions are sparse.
The iteration count is where the speedup appears. Since , for small we have . Therefore, . Each Grover iteration uses one query to , so the same expression gives the query complexity.
For Unique search, , so Grover’s algorithm needs approximately queries. The corresponding success probability is very high: the failure probability is about .
A classical search needs queries on average, so Grover’s algorithm reduces the number of queries from to .
| Search space | Classical, on average | Grover iterations |
|---|---|---|
The rotation picture also explains an important limitation. The success probability is periodic in the iteration count: stopping too early leaves probability on the non-solution side, while continuing past the optimum rotates the state away from the solution direction again. Unlike classical search, where checking more candidates cannot reduce your chances, running more Grover iterations can make the result worse.
The number of solutions also changes the rotation speed. More solutions make larger, so each iteration rotates farther and fewer iterations are needed. The dependence captures this directly: increasing the number of solutions makes the search easier.
There is one extreme case to handle separately. If more than half of the strings are solutions, then . The usual iteration formula gives zero iterations, which is reasonable: if most strings are solutions, simply choosing a string at random already succeeds with probability greater than one half.
The useful regime for Grover’s speedup is therefore the sparse-search regime, where . There, the algorithm reduces the query complexity from classical to .
A natural question is whether a cleverer quantum algorithm could do better than Grover’s quadratic speedup. For unstructured search, the answer is no. Bennett, Bernstein, Brassard and Vazirani proved that every quantum algorithm solving Search with a black-box requires queries.
This matches Grover’s query complexity up to a constant factor, so Grover’s algorithm is optimal. The constant in the unique-search case is optimal as well.
Unknown number of solutions
The optimal iteration count depends on , the number of solutions, but is not always given to the algorithm. Fortunately, a measured candidate is easy to verify: evaluate classically. A failed attempt therefore does not produce a wrong answer—it only means we need to try again.
Instead of choosing one precise iteration count, we can choose the count at random and repeat. With an appropriate randomized schedule, the algorithm finds a solution in queries when solutions exist, and queries when there are none.
A poorly chosen iteration count can waste a single attempt because the state may have rotated past the solution direction. Randomizing the count prevents the algorithm from repeatedly getting stuck at the wrong point in the rotation. The lack of knowledge about therefore costs only a constant factor, not the quadratic speedup.
- 1Draw at random from
- 2Run Grover iterations on
- 3Measure all qubits, giving a string
- 4Check classically: accept it or draw again
Iteration counts tried
Start searching to draw an iteration count and try it. The ceiling here is = 25.
The demo draws from a fixed ceiling, , which is generous whenever solutions turn out to be plentiful. A more sophisticated approach grows the ceiling instead: set , draw uniformly from , and on a failure raise and try again—stopping when the classical check accepts a string, or reporting “no solution” once has climbed past .
The rate of increase has to be carefully balanced. Raise too slowly and the run piles up long shots that were never likely to land, so the queries mount. Raise it too quickly and each attempt overshoots the count it was looking for, and the success probability drops. Growing by a fifth at a time, , works.
From query complexity to real cost
The bound counts only oracle queries. In practice, each query is a full reversible implementation of , and the Grover iterations must run sequentially for a deep, coherent computation. Classical search, by contrast, is easy to distribute across many machines.
So the quadratic speedup is real, given that someone eventually builds a large and stable enough quantum processor. Its cryptographic consequence is simple: Grover effectively halves the security exponent of symmetric key search and hash preimage search:
But a halved exponent is answered by a doubled key. Moving symmetric keys and hashes to the larger sizes restores the original margin exactly, and that is already the standing advice, so the practical significance of the speedup keeps shrinking.
Shor’s algorithm is the sharper threat. It exploits the structure underlying RSA and elliptic-curve cryptography and breaks them outright, where no key size helps. Even there, though, standardised replacements already exist—lattice-based ML-KEM and ML-DSA, hash-based SLH-DSA—and TLS 1.3 already ships hybrid key exchange. The risk table on the cryptography page sorts the primitives along exactly this line—broken by Shor, weakened by Grover, or believed resistant to both.
So for now, quantum algorithms are a great deal more interesting as research than as a practical threat. The theory is settled well ahead of the hardware, and the cryptography that would be affected mostly knows what to do about it already.