View on GitHub
Open this notebook in GitHub to run it yourself
Integer Factorization [1] is a famous problem in number theory: given a composite number , find its prime factors. The importance of the problem stems from there being no known efficient classical algorithm (in the number of bits needed to represent in polynomial time), and much of modern-day cryptography relies on this fact. In 1994, Peter Shor developed an efficient quantum algorithm for the problem [2], providing arguably the most important evidence for an exponential advantage of quantum computing over classical computing.Shor’s algorithm consists of classical parts and a quantum subroutine. The notebook is organized as follows: First, as an introduction, we outline the steps of the algorithm for factoring an input number , summarized from [3]. Then, we construct all the classical and quantum components of the algorithm, and run a simple example. Brief technical details, explaining how the algorithm works, are given together with the implementation, whereas some complex technical details are given at the end of the notebook. The steps of Shor’s algorithm:Complexity: Runs in time, i.e., polynomial in , giving an exponential speedup over the best-known classical factoring algorithms.
- Input: A composite integer .
- Promise: is not a prime power and has at least one nontrivial factor.
- Output: With high probability, a nontrivial factor of .
Keywords: Integer factoring, Order-finding, Period finding, Phase estimation, Hidden subgroup over , RSA/ECC break, Cryptography, Exponential speedup, Modular exponentiation.
- Pick a random number that is co-prime with .
- Find the period of the following function, using the quantum period finding algorithm:
- If is odd or , return to step 1 (this event can be shown to happen with probability at most ).
- Otherwise, are both factors of , and computing one of them yields the required result.
flexible_qpe and Modular Arithmetic.
Finding a co-prime of
This is a simple classical preprocess for the algorithm. We randomly pick an integer in , and check whether it is a co-prime of by calling the Euclidian GCD algorithm. If the sampled integer is not a co-prime then we find a factor of and we are done. (When we run the algorithm for a specific example below, we will fix a co-prime in advance, such that we have a meaningful demo with a quantum part).Output:
Quantum Period Finding as a QPE routine
The core part of Shor’s algorithm, is the period finding of the function : This can be computed via Quantum Phase Estimation (QPE) [4] (QPE was not discussed in the original formulation of Shor’s algorithm but was later proposed by Kitaev [5]) . Recall that the QPE routine, when applied for a unitary and on one of its eigenstates , produces an approximation of the corresponding eigenphase : where and encodes an -bit estimate of (in practice, the estimate is obtained by measurement, and the approximation holds with high probability up to an error of order ). We can find the order by applying QPE for the unitary following the two facts (that are proven at the end of this notebook):- The unitary has eigenstates:
- We can easily prepare an equal superposition of , since
qpe_flexible function, that allows to pass a unitary with a specified powered operation. In particular, in our case we have

Postprocess with continued fractions algorithm
The outcome distribution for thephase_var variable out of the QPE is in , and expected to be peaked around values: for . We can extract the value of by using the continued fractions algorithm: any rational (irrational) number can be written as a finite (infinite) converging sequence of fractions:
There is an efficient classical algorithm for extracting .
For example, using sympy:
Output:
phase_var variable, and calculate the series of rational numbers that correspond to the continued fractions sereis. Then, we pick the fraction with the largest denominator such that , we should see, with high-probability, fractions that fit for .
Let us define a function that applies those steps to a measurment result:
Output:
Verifying the order and factoring
Once is found, we first verify that it is an even number, this is because Shor’s algorithm continues by writing If is even, this equation implies four scenarios:- , impossible, since it contradicts the fact that is the order.
- , in that case we must go back to step 1 and start with a new co-prime .
- , which gives a factoring for .
- with , which means that divides the of the terms on the left. Thus, it has a non-trivial common divisor with one of them, namely, and/or are factors of .
Example: Factoring 21
First, find a co-prime of . We fix this value to in order to get a full end-to-end result that runs the quantum part.Output:
- For the phase variable that approximates the period , we take twice as many qubits as in : this choice provides sufficient accuracy for extracting the period using the continued fraction algorithm (see the Technical Notes at the end of this notebook). In general, increasing the phase size yields deeper circuits with higher success probability of observing , while decreasing it leads to shallower circuits with lower success probability.
Output:

| phase_var | counts | count | probability | bitstring | |
|---|---|---|---|---|---|
| 0 | 0.000000 | 349 | 349 | 0.170410 | 0000000000 |
| 1 | 0.500000 | 347 | 347 | 0.169434 | 1000000000 |
| 2 | 0.833008 | 243 | 243 | 0.118652 | 1101010101 |
| 3 | 0.333008 | 238 | 238 | 0.116211 | 0101010101 |
| 4 | 0.166992 | 229 | 229 | 0.111816 | 0010101011 |
| … | … | … | … | … | … |
| 59 | 0.671875 | 1 | 1 | 0.000488 | 1010110000 |
| 60 | 0.673828 | 1 | 1 | 0.000488 | 1010110010 |
| 61 | 0.836914 | 1 | 1 | 0.000488 | 1101011001 |
| 62 | 0.843750 | 1 | 1 | 0.000488 | 1101100000 |
| 63 | 0.849609 | 1 | 1 | 0.000488 | 1101100110 |
64 rows × 5 columns
Output:

Output:
Technical Notes
The eigenphases and eigenstates of
Below we prove the claim that the modular multiplication by , which is a co-prime of , has the following eigenstates: and the corresponding eigenvalues: where is the order of the function. It is easy to verify that where in the second equality we just changed the sum index , and the third one comes from the fact that the terms under the sum have a period of , and the -th term is equal to the -th one.The initial state for the QPE
Below we show that the state is an equal superposition of . We use the fact that namely, the sum vanishes unless . Calculating explicitly, we getThe size of the phase variable
In Shor’s algorithm, we choose the phase variable to be twice as large as the variablex on which we apply modular multiplication.
This choice follows from the properties of the QPE routine and the continued fractions algorithm.
Applying QPE with a phase variable of size yields an
-bit approximation of the exact phase :
Now, according to the continued fractions algorithm, if we run the it for with ,
then both and can be we can recovered [3]. Thus, performing QPE with gives
which satisfies the requirement of the continued fractions algorithm (the last two inequlities comes from the fact the ).