Skip to main content

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 NN, 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 NN 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.
  • Input: A composite integer NN.
  • Promise: NN is not a prime power and has at least one nontrivial factor.
  • Output: With high probability, a nontrivial factor of NN.
Complexity: Runs in polylog(N)\mathrm{polylog}(N) time, i.e., polynomial in log⁡N\log N, giving an exponential speedup over the best-known classical factoring algorithms.
Keywords: Integer factoring, Order-finding, Period finding, Phase estimation, Hidden subgroup over Z\mathbb{Z}, RSA/ECC break, Cryptography, Exponential speedup, Modular exponentiation.
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 NN, 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:
  1. Pick a random number 1<a<N1 < a < N that is co-prime with NN.
Check co-primality by computing the GCD (greatest common divisor) of aa and NN. If it is 1, then we have a co-prime aa; otherwise, we have a non-trivial factor of NN, and we are done (the GCD complexity is O(log⁡(N))O(\log(N))).
  1. Find the period rr of the following function, using the quantum period finding algorithm:
f(x)=axmod  Nf(x) = a^x\hspace{-8pt} \mod \hspace{-4pt} N
  1. If rr is odd or ar/2=−1 mod Na^{r/2} = -1 \bmod{N}, return to step 1 (this event can be shown to happen with probability at most 1/21/2).
  2. Otherwise, gcd⁡(ar/2±1,N)\gcd(a^{r/2} \pm 1, N) are both factors of NN, and computing one of them yields the required result.
Next, we move to the implementation of each and every step. The quantum part is designed naturally as a Quantum Phase Estimation (QPE) routine, using Classiq’s flexible_qpe and Modular Arithmetic.

Finding a Co-Prime of NN

This is a simple classical preprocess for the algorithm. We randomly pick an integer aa in (1,N)(1,N), and check whether it is a co-prime of NN by calling the Euclidian GCD algorithm. If the sampled integer is not a co-prime then we find a factor of NN and we are done. (When we run the algorithm for a specific example below, we will fix a co-prime aa in advance, such that we have a meaningful demo with a quantum part).
We can run a simple example:
Output:

Quantum Period Finding as a QPE Routine

The core part of Shor’s algorithm, is the period finding of the function f(x)=ax mod Nf(x) = a^x\bmod{N}: Find the minimal integer r such that: ar=1 mod N.\text{Find the minimal integer } r \text{ such that: } a^r =1 \bmod{N} . 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 UU and on one of its eigenstates ∣ψθ⟩|\psi_\theta\rangle, produces an approximation of the corresponding eigenphase θ\theta: ∣ψθ⟩∣0⟩m→QPE(U)∣ψθ⟩∣θ~⟩m,|\psi_{\theta}\rangle|0\rangle_m \xrightarrow[\text{QPE}(U)]{} |\psi_{\theta}\rangle|\tilde{\theta}\rangle_m , where U∣ψθ⟩=e2πiθ∣ψθ⟩U|\psi_\theta\rangle = e^{2\pi i \theta}|\psi_\theta\rangle and ∣θ~⟩m|\tilde{\theta}\rangle_m encodes an mm-bit estimate of θ\theta (in practice, the estimate θ~\tilde{\theta} is obtained by measurement, and the approximation holds with high probability up to an error of order 1/2m1/2^m). We can find the order rr by applying QPE for the unitary Ua∣x⟩=∣ax mod N⟩,U_a|x\rangle = |ax\bmod{N}\rangle, following the two facts (that are proven at the end of this notebook):
  1. The unitary UaU_a has rr eigenstates:
∣ψs⟩≡1r∑k=0r−1e−2πisk/r∣ak mod N⟩ with eigenvalues λs=e2πis/r,s=0,1,…,r−1.|\psi_s\rangle\equiv \frac{1}{\sqrt{r}}\sum^{r-1}_{k=0}e^{-2\pi i sk/r}|a^{k}\bmod{N}\rangle \text{ with eigenvalues } \lambda_s = e^{2\pi i s/r}, \qquad s=0,1,\dots, r-1.
  1. We can easily prepare an equal superposition of ∣ψs⟩|\psi_s\rangle, since
∣1⟩=1r∑k=0r−1∣ψs⟩.|1\rangle = \frac{1}{\sqrt{r}}\sum^{r-1}_{k=0}|\psi_s\rangle. Therefore, by applying a QPE for UaU_a, on the state ∣1⟩|1\rangle, we get an equal superposition for the estimation of the eigenphases {s/r}s=0r−1\{s/r\}^{r-1}_{s=0}: ∣1⟩∣0⟩m→QPE(Ua)1r∑s=0r−1∣ψs⟩∣s/r~⟩m.|1\rangle|0\rangle_m \xrightarrow[\text{QPE}(U_a)]{} \frac{1}{\sqrt{r}}\sum^{r-1}_{s=0}|\psi_{s}\rangle|\tilde{s/r}\rangle_m. How to extract the period rr from the resulting state is shown in the following section. In this section we focus on the implementation of the quantum part. We work with the qpe_flexible function, that allows to pass a unitary with a specified powered operation. In particular, in our case we have (Ua)p∣x⟩=∣apx mod N⟩\left(U_a\right)^{p}|x\rangle =|a^p x\bmod{N}\rangle
Screenshot 2025-09-30 at 12.15.53.png

Postprocess with Continued Fractions Algorithm

The outcome distribution for the phase_var variable out of the QPE is in [0,1)[0,1), and expected to be peaked around rr values: s/rs/r for s=0,1,…,r−1s=0,1,\dots, r-1. We can extract the value of rr by using the continued fractions algorithm: any rational (irrational) number can be written as a finite (infinite) converging sequence of fractions: x=a0+1a1+1a2+1a3+⋱.x = a_0 + \cfrac{1}{a_1 + \cfrac{1}{a_2 + \cfrac{1}{a_3 + \ddots}}} . There is an efficient classical algorithm for extracting aia_i. For example, using sympy:
Output:
Thus, we can extract rr by taking a measurment of the phase_var variable, and calculate the series of rational numbers pi/qip_i/q_i that correspond to the continued fractions sereis. Then, we pick the fraction with the largest denominator qiq_i such that qi<Nq_i<N, we should see, with high-probability, fractions that fit s/rs/r for s=0,1,…,r−1s=0,1,\dots, r-1. Let us define a function that applies those steps to a measurment result:
Let us see an example, consider the following results out of the period finding algorithm, for N=18N=18:
Our postprocess function gives
Output:
We can see that in this case one can conclude that r=5r=5 is the period we were trying to find.

Verifying the Order and Factoring

Once rr is found, we first verify that it is an even number, this is because Shor’s algorithm continues by writing ar=1 mod N  ⟹  (ar/2−1)(ar/2+1)=0 mod N.a^r=1\bmod{N}\implies \left(a^{r/2}-1\right)\left(a^{r/2}+1\right) = 0 \bmod{N}. If rr is even, this equation implies four scenarios:
  1. (ar/2−1)=0 mod N\left(a^{r/2}-1\right) = 0 \bmod{N}, impossible, since it contradicts the fact that rr is the order.
  2. (ar/2+1)=0 mod N\left(a^{r/2}+1\right) = 0 \bmod{N}, in that case we must go back to step 1 and start with a new co-prime aa.
  3. (ar/2−1)(ar/2+1)=N\left(a^{r/2}-1\right)\left(a^{r/2}+1\right) = N, which gives a factoring for NN.
  4. (ar/2−1)(ar/2+1)=kN\left(a^{r/2}-1\right)\left(a^{r/2}+1\right) = kN with k>1k>1, which means that NN divides the of the terms on the left. Thus, it has a non-trivial common divisor with one of them, namely, gcd(ar/2+1,N)≠1\mathrm{gcd}(a^{r/2}+1,N)\neq 1 and/or gcd(ar/2−1,N)≠1\mathrm{gcd}(a^{r/2}-1,N)\neq 1 are factors of NN.
It can be shown that the situations in which rr is odd or (ar/2+1)=0 mod N\left(a^{r/2}+1\right) = 0 \bmod{N} can happen at probability 1/2 at most. Below we define a function that verifies we are not in the second possibility, and returns the factors on NN in case we are at the last two.

Example: Factoring 21

First, find a co-prime of NN. We fix this value to a=11a=11 in order to get a full end-to-end result that runs the quantum part.
Output:
Next, we run the quantum period finding algorithm to extract the period rr. Concerning the size of the quantum variables:
  • For the phase variable that approximates the period rr, we take twice as many qubits as in ∣x⟩|x\rangle: 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 s/rs/r, while decreasing it leads to shallower circuits with lower success probability.
Output:
Screenshot 2025-09-30 at 12.16.15.png We execute and postprocess the results with the continued fraction approximation. For the demonstration, let us postprocess all the results with more than 10 counts.
Output:
Output:
phase_var counts probability bitstring
0 0.500000 355 0.173340 1000000000
1 0.000000 314 0.153320 0000000000
2 0.833008 248 0.121094 1101010101
3 0.166992 241 0.117676 0010101011
4 0.666992 238 0.116211 1010101011
… … … … …
67 0.677734 1 0.000488 1010110110
68 0.810547 1 0.000488 1100111110
69 0.838867 1 0.000488 1101011011
70 0.840820 1 0.000488 1101011101
71 0.842773 1 0.000488 1101011111

72 rows × 4 columns

Output:
We can see that the period is r=6r=6, as can be read from all the results that are post-processed to 1/61/6 or 5/65/6. Let us plot the full distribution, together with the continued fraction approximation:
output We can clearly see that we have peaks at 06,16,26,36,46,56\frac{0}{6}, \frac{1}{6}, \frac{2}{6}, \frac{3}{6} , \frac{4}{6}, \frac{5}{6}, that is, the order is r=6r=6.
All is left is to run the final step that determines the factor of NN out of aa and rr:
Output:

Technical Notes

The Eigenphases and Eigenstates of f(x)=ax mod Nf(x) = ax\bmod{N}

Below we prove the claim that the modular multiplication by aa, which is a co-prime of NN, has the following eigenstates: ∣ψs⟩=1r∑k=0r−1e−2πisk/r∣ak mod N⟩,s=0,1,…,r−1,|\psi_s\rangle = \frac{1}{\sqrt{r}}\sum^{r-1}_{k=0}e^{-2\pi i sk/r}|a^{k}\bmod{N}\rangle, \qquad s=0,1,\dots, r-1, and the corresponding eigenvalues: λs=e2πis/r,\lambda_s = e^{2\pi i s/r}, where rr is the order of the function. It is easy to verify that a∣ψs⟩=1r∑k=0r−1e−2πisk/r∣ak+1 mod N⟩=1r∑k=1re2πis/re−2πisk/r∣ak mod N⟩=e2πis/r1r∑k=0r−1e−2πisk/r∣ak mod N⟩=e2πis/ra∣ψs⟩,a|\psi_s\rangle = \frac{1}{\sqrt{r}}\sum^{r-1}_{k=0}e^{-2\pi i sk/r}|a^{k+1}\bmod{N}\rangle = \frac{1}{\sqrt{r}}\sum^{r}_{k=1}e^{2\pi i s/r}e^{-2\pi i sk/r}|a^{k}\bmod{N}\rangle = e^{2\pi i s/r}\frac{1}{\sqrt{r}}\sum^{r-1}_{k=0}e^{-2\pi i sk/r}|a^{k}\bmod{N}\rangle = e^{2\pi i s/r}a|\psi_s\rangle, where in the second equality we just changed the sum index k→k−1k \rightarrow k-1, and the third one comes from the fact that the terms under the sum have a period of rr, and the rr-th term is equal to the 00-th one.

The Initial State ∣1⟩|1\rangle for the QPE

Below we show that the state ∣1⟩|1\rangle is an equal superposition of ∣ψs⟩|\psi_s\rangle. We use the fact that ∑k′=0r−1e−2πik′k/r=r⋅δk0,\sum^{r-1}_{k'=0} e^{-2\pi i k'k/r} = r\cdot \delta_{k0}, namely, the sum vanishes unless k=0k=0. Calculating explicitly, we get 1r∑k′=0r−1∣ψk′⟩=1r∑k′=0r−1∑k=0r−1e−2πik′k/r∣ak mod N⟩=1r∑k=0r−1(∑k′=0r−1e−2πik′k/r)∣ak mod N⟩=1r∑k=0r−1rδk0∣ak mod N⟩=∣1⟩.\frac{1}{\sqrt{r}}\sum^{r-1}_{k'=0}|\psi_{k'}\rangle = \frac{1}{r}\sum^{r-1}_{k'=0} \sum^{r-1}_{k=0}e^{-2\pi i k'k/r}|a^{k}\bmod{N}\rangle =\frac{1}{r}\sum^{r-1}_{k=0} \left(\sum^{r-1}_{k'=0} e^{-2\pi i k'k/r}\right)|a^{k}\bmod{N}\rangle =\frac{1}{r}\sum^{r-1}_{k=0} r\delta_{k0}|a^{k}\bmod{N}\rangle = |1\rangle.

The Size of the Phase Variable

In Shor’s algorithm, we choose the phase variable to be twice as large as the variable x 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 mm yields an mm-bit approximation of the exact phase s/rs/r: ∣j2m−sr∣≤12m+1, for some 0≤j≤2m−1.\left| \frac{j}{2^m}-\frac{s}{r}\right|\leq \frac{1}{2^{m+1}}, \text{ for some } 0\leq j\leq 2^{m-1}. Now, according to the continued fractions algorithm, if we run the it for θ\theta with ∣sr−θ∣≤12r2\left| \frac{s}{r}-\theta\right|\leq \frac{1}{2r^2}, then both jj and rr can be we can recovered [3]. Thus, performing QPE with m=2nm=2n gives ∣j2m−sr∣≤122n+1≤12⋅N2≤12⋅r2,\left| \frac{j}{2^m}-\frac{s}{r}\right|\leq \frac{1}{2^{2n+1}}\leq \frac{1}{2\cdot N^{2}} \leq \frac{1}{2\cdot r^{2}}, which satisfies the requirement of the continued fractions algorithm (the last two inequlities comes from the fact the r≤N≤2nr\leq N\leq 2^n).

References

[1]: Integer Factorization (Wikipedia) [2]: P. W. Shor, “Algorithms for quantum computation: Discrete logarithms and factoring,” Proceedings 35th Annual Symposium on Foundations of Computer Science (FOCS), IEEE, 1994. [3]: Shor’s Algorithm Procedure (Wikipedia) [4]: M. A. Nielsen & I. L. Chuang, “Quantum Computation and Quantum Information”, Cambridge Univ. Press, 2001. ISBN 978-9812388582. [5]: Kitaev, A. Yu. “Quantum measurements and the Abelian Stabilizer Problem”. arXiv:quant-ph/9511026 (1995).