Quantum Algorithms
Quantum algorithms make use of superposition, interference and entanglement to solve certain problems faster than classical methods. This page summarises several influential algorithms and suggests simple circuits you can try on the Quantum Simulator .
Several oracle algorithms below share a pattern: prepare a superposition, encode function information in relative phases, and use interference to change the probabilities of measurable outcomes. Other algorithms on this page, including phase estimation and variational methods, use different structures.
Phase Kickback and Oracles
Most of the algorithms below query a Boolean function through a reversible oracle
Prepare the output qubit in by starting it in |1⟩ and applying H. Then multiplies the branch by :
The output qubit remains in and is separable from the input, while the function value has been “kicked back” into the input branch’s phase. This trick enables the one-query Deutsch-Jozsa and Bernstein-Vazirani algorithms below.
Deutsch-Jozsa Algorithm
The Deutsch-Jozsa algorithm is given a promise: the function is either constant (the same value on every input) or balanced (returns 0 on exactly half of the inputs). It decides which with a single query. A deterministic classical algorithm needs queries in the worst case, since seeing equal values still leaves both cases open. (A randomised classical algorithm gets the answer with high probability after a handful of queries, so the exponential separation here is specific to the deterministic setting; Simon’s problem below gives a stronger one.)
The circuit is:
- Prepare input qubits in
|0⟩and one output qubit in|1⟩. - Apply
Hto all qubits, giving . - Apply the oracle once, which by phase kickback produces .
- Apply
Hto the input qubits and measure them.
The amplitude of the all‑zeros outcome is . For a constant every term has the same sign and that amplitude is , so the measurement returns with certainty. For a balanced the and terms cancel exactly and is never observed. Measuring all zeros therefore means constant, and any other outcome means balanced.
Bernstein-Vazirani Algorithm
The Bernstein-Vazirani algorithm recovers a hidden bit string from an oracle computing , the parity of the bits of selected by . Classically each query reveals one bit of information, so queries are needed; the quantum algorithm needs only one.
The circuit is identical to Deutsch-Jozsa: Hadamards on the input register, one oracle call with the output qubit in , then Hadamards again. After the kickback the register holds , and the second Hadamard layer maps that state exactly onto ; so measuring the input qubits reads the hidden string off directly, with probability 1.
Simon’s Algorithm
Simon’s problem provides a function with the promise that exactly when or , for an unknown non‑zero string . Finding with bounded error classically requires oracle queries, while the quantum algorithm uses queries, an exponential separation.
Hadamard gates on the input qubits create a superposition, the oracle writes into a second register of the same size, and a second round of Hadamards on the input register is followed by measurement. Every outcome that can appear satisfies
because the two branches and share an output value and interfere destructively unless that condition holds. Each run therefore yields one linear equation over , drawn uniformly from the strings orthogonal to . Collecting linearly independent equations takes expected runs because some outcomes duplicate information already held. Gaussian elimination modulo 2 then leaves a one‑dimensional solution space , whose nonzero member is .
Quantum Fourier Transform
The Quantum Fourier transform (QFT) is the quantum analogue of the discrete Fourier transform. It maps computational basis states to phase‑encoded superpositions and is the engine behind phase estimation and Shor’s algorithm. For an ‑qubit input state , writing ,
As a matrix, the entry in row and column (both indexed from 0) is with :
The rows are mutually orthogonal because the sum of the relevant powers of is zero for every pair of distinct rows. With the normalization, this makes the matrix unitary. For a single qubit, and the matrix is the Hadamard gate.
Product form and the circuit
Writing in binary ( the most significant bit) and using the binary‑fraction notation , the transform factorises completely:
The QFT of each computational-basis state has the product form above and is therefore unentangled. The QFT can nevertheless create entanglement for other product inputs and can transform entanglement already present in its input.
This factorisation is exactly the circuit. Define the controlled phase rotation
so that and . For each qubit in turn, apply H to qubit and then a controlled‑ on qubit for every later qubit acting as control. Because the product form builds the output bits in reverse order, the circuit finishes by reversing the register with swap gates.
For two qubits this reads: H on the first qubit, a controlled‑ between the two, H on the second qubit, and finally a swap. The controlled phase gate is diagonal, so it does not matter which of the two qubits you designate as the control.
The exact circuit uses Hadamards, controlled rotations and swaps, for elementary gates if those controlled rotations are available. A classical fast Fourier transform of an explicit list of amplitudes costs . These costs solve different input/output problems, so their comparison is not a drop‑in speedup for classical Fourier analysis: efficiently loading arbitrary classical amplitudes is not free, and measurement cannot reveal all output amplitudes. The QFT is useful as a coherent subroutine, for example when extracting periodicity through phase estimation.
Phase Estimation
Phase estimation estimates an eigenphase of a unitary when the corresponding eigenstate can be prepared. If , the algorithm produces an estimate of . It is a key subroutine in standard presentations of Shor’s algorithm and HHL.
The circuit uses two registers: counting qubits prepared in |0⟩ and put into superposition with Hadamards, and a second register prepared in the eigenstate . That second register is not simply initialised to |0⟩: the algorithm needs an eigenvector of to act on. For some unitaries a computational basis state happens to be one, but in general has to be prepared. Feeding in a superposition of eigenstates also works; the measurement then returns the phase of one of them, chosen at random with probability given by its weight.
Controlled‑ operations, one for each counting qubit , kick the phase back onto the counting register, leaving it in
If is an integer , this phase-gradient state is exactly . In general it is not the QFT of a computational-basis state, but applying the inverse QFT still produces a distribution concentrated near the integers closest to . Dividing a measured integer by estimates . Using the forward QFT with the same sign convention reflects the estimate to , so the direction matters. If has an exact ‑bit binary expansion, the result is deterministic. Otherwise, the probability of the nearest integer is at least ; using extra counting qubits and rounding to the desired precision can raise the success probability as high as required.
Shor’s Factoring Algorithm
Shor’s algorithm factors an ‑bit integer with bounded error in time polynomial in . It combines classical pre‑ and post‑processing with a quantum routine for order finding. Related instances of Shor’s algorithm solve discrete logarithms, threatening widely used public-key systems based on factoring or discrete-logarithm assumptions.
Pick a random with ; if that gcd is already a factor. Otherwise the quantum routine finds the order of modulo , the smallest with . It does so by applying phase estimation to the unitary : a counting register of about qubits is placed in superposition, modular exponentiation controlled by those qubits is applied, and the inverse QFT is performed.
Measuring the counting register yields an integer for which is likely to approximate for some integer . Continued fractions generate a candidate denominator; it must be checked because a sample may reveal only a divisor of . If the recovered order is even and , then yield non‑trivial factors. After easy classical cases such as even integers and prime powers are handled, random choices of and repeated quantum samples give a bounded-error polynomial-time algorithm.
Grover’s Search Algorithm
Grover’s algorithm finds a marked item in an unstructured search space of size using queries, a quadratic improvement over the classical query complexity. For a uniformly located item checked without replacement, a classical search uses queries on average. Grover’s scaling is optimal in the quantum black-box query model: any bounded-error quantum algorithm for this problem needs queries.
Starting from the uniform superposition , each Grover iteration applies two reflections:
- The oracle flips the sign of the marked state, , leaving all others alone.
- The diffusion operator reflects every amplitude about the mean, converting the sign flip into an increase in magnitude.
Together they rotate the state vector by a fixed angle towards in the two‑dimensional plane spanned by and the uniform superposition. After iterations the success probability is where , which is maximised at roughly iterations. Note that this is a rotation, not a ratchet: running too many iterations rotates past the target and the success probability falls again.
The two‑qubit version is the nicest one to build on the Quantum Simulator: with a single iteration rotates the state exactly onto the marked item, so one oracle plus one diffusion step finds it with probability 1.
Grover’s algorithm generalises to amplitude amplification, which boosts the success probability of any procedure that prepares a state with some amplitude on a “good” subspace, and this in turn underpins quantum counting and amplitude estimation.
Variational Algorithms
Noisy intermediate‑scale quantum devices often employ variational algorithms. Here a parameterised quantum circuit is optimised using classical feedback. Examples include the Variational Quantum Eigensolver for estimating molecular ground‑state energies and the Quantum Approximate Optimisation Algorithm for combinatorial problems. These approaches are well suited to interactive exploration because the circuits are relatively small but depend on tunable parameters.
A cost function, such as the expectation value of a Hamiltonian, is estimated from repeated measurements of the circuit. A classical optimiser then updates the parameters to reduce this cost, and the process iterates until convergence. For a normalized trial state and an exact expectation value of the intended Hamiltonian, the variational principle makes that expectation an upper bound on the true ground-state energy. A finite-shot or noise-biased estimate can fall below the exact energy and is not automatically a rigorous bound. Unlike the algorithms above, these methods have no general proven speedup; performance is problem- and implementation-dependent, and training can stall on flat regions of the parameter landscape.
HHL
The Harrow-Hassidim-Lloyd algorithm prepares a quantum state proportional to the solution of . Its complexity can depend only polylogarithmically on the dimension under strong input and output assumptions, but it also depends polynomially on parameters such as sparsity, condition number and inverse precision. Efficient access to , efficient preparation of , and a well-conditioned system are therefore essential. With Hermitian (a general matrix can be embedded in a larger Hermitian one), the original algorithm uses phase estimation on , a controlled rotation whose successful branch weights an eigencomponent by approximately , and uncomputation.
The output is a quantum state proportional to the solution vector rather than a classical list of coefficients. Reconstructing all components generally removes an exponential-in-dimension advantage, so applications must extract a property of the solution state efficiently, such as an observable expectation value. The resulting end-to-end advantage depends on the data-access, conditioning, precision and measurement costs.
These algorithms illustrate several ways quantum gates can manipulate amplitudes and phases. Their speedups and practical requirements differ substantially, and small-scale simulator examples are useful for understanding their state transformations rather than demonstrating large-scale computational advantage.
Simulator Lab: Use Small Instances to Debug Algorithms
The Quantum Simulator includes Oracle, Diffusion, controlled phase and rotation gates as well as a Grover (2) preset. These are best used to inspect amplitude flow on small registers, not to benchmark a claimed quantum speedup in a classical browser.
QSim does not expose arbitrary custom unitaries, modular-arithmetic blocks or a general controlled- constructor. Consequently, Grover search and a small QFT map directly onto the current palette, while full phase estimation, Shor and HHL would first require nontrivial decompositions into supported gates. A conceptual section appearing on this page does not imply that its complete scalable circuit is available as one QSim preset.
Use this compatibility guide before trying to translate an algorithm into the builder:
| Topic on this page | Directly supported? | Best QSim use |
|---|---|---|
| Phase kickback | Partly | Reproduce it with explicit supported controlled gates; the built-in marked-state Oracle is not the general defined above |
| Deutsch-Jozsa | No general Boolean-function oracle | Build only hand-decomposed examples whose can be expressed with available gates |
| Bernstein-Vazirani | No dedicated preset | Implement small linear oracles as CNOTs selected by the bits of |
| Simon | No general two-register oracle | Study the surrounding Hadamards conceptually; a promised two-to-one must be decomposed separately |
| QFT | Yes, for small registers | Combine H, controlled phase and Swap as in the lab below |
| Phase estimation | Not as a generic routine | Possible only after manually decomposing every controlled power of a chosen |
| Shor | No modular exponentiation block | Use the QFT section for component-level intuition, not an end-to-end factoring claim |
| Grover | Yes | Use Oracle, Diffusion or the Grover (2) preset |
| Variational algorithms | No optimizer or Hamiltonian-term workflow | Explore parameterized rotations manually, recording each expectation estimate outside QSim |
| HHL | No matrix-input or Hamiltonian-simulation interface | Treat the section as theory rather than a runnable QSim recipe |
The built-in Oracle is a diagonal phase operation that multiplies one selected computational-basis state by . It is exactly the form needed for the single-marked-item Grover exercise. It should not be substituted silently for an arbitrary Boolean oracle, a Simon oracle or modular exponentiation, since those operations have different input and output registers and different promises.
Build Bernstein-Vazirani without a preset
The linear oracle for Bernstein-Vazirani decomposes particularly simply. To recover a three-bit string :
- Create four qubits. Use
q0,q1,q2as the input andq3as the output ancilla. - Toggle
q3to 1. The initial integer is 8 and QSim displays|1000⟩becauseq3is the leftmost displayed bit. - Add
Hto all four qubits. - For every position where , add CNOT targets
j,3. These CNOTs implement . - Add
Htoq0,q1,q2and run.
For example, for , add CNOT 0,3 and CNOT 2,3. The input qubits finish as q2q1q0 = 101 with probability 1. The output ancilla remains in , so the complete computational-basis result table has two equally likely rows that differ only in q3. Read the three rightmost displayed bits, or inspect the input-qubit Z components, rather than expecting the entire four-qubit result to be one basis state.
This construction is a useful debugging exercise because each hidden-string bit corresponds to exactly one optional CNOT. Export the zero-string circuit first, then add one CNOT at a time and confirm that only its associated recovered input bit changes.
Compare constant and balanced Deutsch-Jozsa oracles
A two-input example also fits the available gates. Use q0,q1 for the inputs and q2 for the output ancilla:
- Toggle
q2to 1, giving initial integer 4 and displayed ket|100⟩. - Add
Hto all three qubits. - Insert one of the small oracle decompositions below.
- Add
Htoq0,q1and run.
| Function | Promised type | Oracle gates between Hadamard layers | Final input q1q0 |
|---|---|---|---|
| constant | none | 00 | |
| constant | X on q2 | 00 | |
| balanced | CNOT 0,2 | 01 | |
| balanced | CNOT 1,2 | 10 | |
| balanced | CNOT 0,2, then CNOT 1,2 | 11 |
The algorithm’s decision rule uses only whether the two input bits are 00; it does not require identifying which balanced function was supplied. As in the Bernstein-Vazirani exercise, the ancilla remains , so two complete three-qubit basis rows can appear. Ignore the leftmost displayed ancilla bit when applying the constant-versus-balanced decision rule.
These examples do not turn QSim’s marked-state Oracle button into a Deutsch-Jozsa oracle. They explicitly decompose a few operations using X and CNOT, which is why their behavior matches the oracle definition at the start of this page.
Grover search with a visible marked state
Load Grover (2) and run it. One basis state should have probability 1 after the single Grover iteration. Then rebuild the circuit manually:
- Add
Htoq0andq1to prepare the uniform superposition. - Enter targets
0,1, selectOracle, and set Oracle marked state (int) from 0 through 3. The integer is interpreted within the selected target list. - Select
Diffusionfor the same two qubits. - Run after each marked-state change and confirm that the probability-one output moves accordingly.
For an Oracle acting on targets 0,1, marked integer 2 has local bits 10 with the first selected qubit carrying the least significant local bit. Because the displayed ket places q0 on the right, always use the output table rather than guessing from the integer’s printed binary form.
One iteration succeeds exactly for . Adding a second Oracle and Diffusion pair reduces the success probability again, which directly demonstrates Grover’s rotation rather than monotonic amplification.
Build a two-qubit QFT
QSim displays q1 as the most significant bit in a two-qubit ket. To implement the convention used in the formula above, add H to q1, controlled phase on targets 0,1 with angle , H to q0, and Swap on 0,1. Target order does not affect the symmetric controlled-phase gate. Test all four initial basis states by changing Initial basis state and rerunning.
The computational-basis probabilities are uniform for every basis input, so they cannot verify the phases by themselves. Inspect the local Bloch angles or append an inverse-QFT circuit and check that each input is recovered. This is a recurring simulator lesson: a probability histogram can validate magnitudes while missing phase errors.
Use JSON as an algorithm test fixture
Export a known-good circuit before experimenting. For each modification, record:
- register size and displayed initial ket;
- operation changed and its target order;
- expected nonzero outputs or expected deterministic output;
- shot count if sampled branches are involved.
Importing the same JSON before each trial prevents accidental gate accumulation. Export CSV is useful for comparing full basis-state probabilities numerically, while Export PNG is useful for documenting the gate order. Use both when an exercise needs to be reproducible and readable.