If a large enough quantum computer existed, the RSA signature of a website and the Diffie-Hellman key exchange would stop protecting anything. That is the promise, or the threat, of Shor's algorithm. But the algorithm does not "break" anything by itself: it finds the period of a function, and everything else is arithmetic that a laptop already does. Understanding where the quantum work ends and the classical work begins is the quickest way to judge what Shor can do today, what it cannot do, and why cryptography is moving toward other mathematical problems.
This article builds the algorithm on small numbers (15, 21, 35) with a numpy simulation, and checks every result against a second, independent calculation. It then covers the reduction to the period, the quantum Fourier transform, the circuit that finds the period, Gidney's resource estimates and the state of the NIST standards. You need the gates from article 02 and the entanglement from article 03; the previous algorithm in the series, Grover, appears only as a point of comparison.
From factoring to finding a period
Take N = 15 and a base a = 7 coprime to 15. The powers of 7 modulo 15 are 7, 4, 13, 1 and then they repeat: 7 to the fourth is 2401, that is 160 times 15 plus 1. The smallest exponent r with a^r ≡ 1 (mod N) is called the order of a modulo N; here r = 4. If r is even you can write (a^(r/2) - 1)(a^(r/2) + 1) ≡ 0 (mod N): with r = 4 these are 48 and 50. Their product is a multiple of 15, but neither 48 nor 50 is, so 15 is split between the two factors and the greatest common divisor with each one reveals a factor: gcd(48, 15) = 3 and gcd(50, 15) = 5.
This reduction is entirely classical. The expensive step is finding r when N has hundreds of digits: no efficient classical method is known. The method can also fail in three ways, which you should know before looking for a period:
- the base
ashares a factor withN: in that case thegcdis already a factor and no quantum algorithm is needed; - the order
ris odd, and cannot be divided by two; a^(r/2) ≡ -1 (mod N): then one of the two factors is a multiple ofNand thegcdreturns only 1 orN.
The first two cases are recognised immediately; the third shows up only after r has been found, and forces you to repeat with another base: with an unlucky choice a whole quantum run is thrown away. The following listing enumerates all the bases for three moduli and counts how many work, with no quantum computation at all.
from math import gcd
def ordine(a, N):
r = 1
while pow(a, r, N) != 1:
r += 1
return r
for N in (15, 21, 35):
buoni, cattivi = [], []
for a in range(2, N):
if gcd(a, N) != 1:
continue
r = ordine(a, N)
riuscito = r % 2 == 0 and pow(a, r // 2, N) != N - 1
(buoni if riuscito else cattivi).append((a, r))
tot = len(buoni) + len(cattivi)
print(f"N={N}: {len(buoni)} bases out of {tot} give a factor, failed examples {cattivi[:4]}")
# How fast the state to simulate grows: t = 2n counting qubits + n work qubits
for bit in (4, 5, 6, 11, 2048):
amplitudes = 2 ** (3 * bit)
print(f"n={bit}: 2^{3 * bit} amplitudes" + (f" (~{amplitudes:.1e})" if bit < 100 else f" (a number with {len(str(amplitudes))} digits)"))
# Output:
# N=15: 6 bases out of 7 give a factor, failed examples [(14, 2)]
# N=21: 6 bases out of 11 give a factor, failed examples [(4, 3), (5, 6), (16, 3), (17, 6)]
# N=35: 18 bases out of 23 give a factor, failed examples [(11, 3), (16, 3), (19, 6), (24, 6)]
# n=4: 2^12 amplitudes (~4.1e+03)
# n=5: 2^15 amplitudes (~3.3e+04)
# n=6: 2^18 amplitudes (~2.6e+05)
# n=11: 2^33 amplitudes (~8.6e+09)
# n=2048: 2^6144 amplitudes (a number with 1850 digits)
The while loop in ordine is the brute-force search for the order: fine for 35, and for a 2048-bit modulus it would never terminate. The riuscito branch applies the two conditions stated above. For 15 only base 14 fails (it is congruent to -1: r = 2 and a^(r/2) = -1); for 21, 6 bases out of 11 work, for 35, 18 out of 23. With three moduli I do not derive a general rule: the fraction changes from modulus to modulus, and that is why the algorithm retries with different bases. The last lines anticipate a problem treated further on: simulating a modulus of n bits requires 2^(3n) amplitudes (2n counting qubits plus n work qubits), and already at 11 bits that is 8.6 billion complex numbers.
The quantum Fourier transform
To read a period you need a Fourier transform. A signal that repeats every 4 samples has peaks at the frequencies that are multiples of a quarter of the sampling rate: it is the same idea. The QFT on n qubits applies the discrete transform to the 2^n amplitudes of the state using only one- and two-qubit gates: one Hadamard per qubit, one controlled phase for each pair, and at the end some swaps that reverse the order of the bits. That is n + n(n-1)/2 + n/2 gates, so the cost grows with the square of n.
The listing builds the circuit as a product of matrices and compares it with the matrix of the discrete transform. The functions cphase, hadamard and swap produce the three gates as 2^n × 2^n matrices; qft_circuito composes them starting from the most significant qubit. If you forgot the final swaps, the matrix would stay unitary but would no longer coincide with the DFT: that is what the comparison line catches.
import numpy as np
def cphase(n, controllo, bersaglio, angolo):
"""2^n x 2^n matrix: phase e^{i*angle} if both qubits are 1."""
d = np.ones(2**n, dtype=complex)
for s in range(2**n):
if (s >> controllo) & 1 and (s >> bersaglio) & 1:
d[s] = np.exp(1j * angolo)
return np.diag(d)
def hadamard(n, q):
H = np.array([[1, 1], [1, -1]]) / np.sqrt(2)
ops = [np.eye(2)] * n
ops[n - 1 - q] = H # qubit 0 is the least significant bit
M = ops[0]
for o in ops[1:]:
M = np.kron(M, o)
return M
def swap(n, a, b):
P = np.zeros((2**n, 2**n))
for s in range(2**n):
ba, bb = (s >> a) & 1, (s >> b) & 1
t = s & ~(1 << a) & ~(1 << b) | (bb << a) | (ba << b)
P[t, s] = 1
return P
def qft_circuito(n):
U = np.eye(2**n, dtype=complex)
for j in reversed(range(n)):
U = hadamard(n, j) @ U
for k in reversed(range(j)):
U = cphase(n, k, j, np.pi / 2 ** (j - k)) @ U
for i in range(n // 2):
U = swap(n, i, n - 1 - i) @ U
return U
for n in (3, 5, 8):
N = 2**n
dft = np.exp(2j * np.pi * np.outer(range(N), range(N)) / N) / np.sqrt(N)
U = qft_circuito(n)
print(f"n={n}: gates={n + n * (n - 1) // 2 + n // 2}, "
f"equal to the DFT (deviation < 1e-10)={bool(np.abs(U - dft).max() < 1e-10)}, "
f"unitary={np.allclose(U.conj().T @ U, np.eye(N))}")
# Output:
# n=3: gates=7, equal to the DFT (deviation < 1e-10)=True, unitary=True
# n=5: gates=17, equal to the DFT (deviation < 1e-10)=True, unitary=True
# n=8: gates=40, equal to the DFT (deviation < 1e-10)=True, unitary=True
The output confirms that the circuits of 7, 17 and 40 gates coincide with the DFT for 3, 5 and 8 qubits and are unitary. The test holds only for these three sizes. This code is not a practical simulator, because it builds dense matrices; in the rest of the article the QFT is applied with numpy.fft, the same transform at negligible cost.
The circuit that finds the period
The counting register has t qubits, the work register n, equal to the number of bits of N. You start from zero in the counting register and from 1 in the work register; a Hadamard on every counting qubit creates the uniform superposition of all the x from 0 to 2^t - 1. Then the modular exponentiation takes |x⟩|1⟩ to |x⟩|a^x mod N⟩: the work register holds the periodic function, entangled with the x that generated it. Finally the QFT on the counting register and the measurement.
Why does the measurement reveal the period? Measuring the work register leaves the counting register in a superposition of the x that give the same value, that is x0, x0 + r, x0 + 2r, ...: a comb with spacing r. The transform of a comb with spacing r is a comb with spacing 2^t / r, so the measurement gives a k close to a multiple of 2^t / r, with k / 2^t ≈ s / r for a random integer s. You have no control over s, and this is one of the reasons the classical part is needed.
The listing simulates everything for a given N and a. In distribuzione the loop directly builds the state after the Hadamards and the oracle: amplitude 1/√M on the pair (x, a^x mod N); the QFT is a transform along the counting axis, and the probability of each k sums the squared amplitudes over the work register. formula_chiusa computes the same distribution with a geometric sum, without building the state: it is the second, independent calculation. da_k_a_fattore is the classical part: Fraction(k, 2**t).limit_denominator(N) finds the fraction closest to k/2^t with denominator at most N, and that denominator is the candidate for r.
from fractions import Fraction
from math import gcd, pi, sin
import numpy as np
def distribuzione(N, a, t):
"""Probability of each outcome k of the counting register (t qubits)."""
n = N.bit_length() # qubits of the work register
M = 2**t
psi = np.zeros((M, 2**n), dtype=complex)
for x in range(M): # Hadamard on the counting register
psi[x, pow(a, x, N)] = 1 / np.sqrt(M) # + oracle |x>|1> -> |x>|a^x mod N>
psi = np.fft.ifft(psi, axis=0) * np.sqrt(M) # QFT on the counting register
return (np.abs(psi) ** 2).sum(axis=1)
def formula_chiusa(N, a, t, r):
"""Same distribution, without simulating: geometric sum for each x0 < r."""
M = 2**t
P = np.zeros(M)
for k in range(M):
for x0 in range(r):
m = (M - x0 + r - 1) // r # how many x equal x0 + j*r, with x < 2^t
d = sin(pi * k * r / M)
ampl = m if abs(d) < 1e-12 else sin(pi * k * r * m / M) / d
P[k] += ampl**2 / M**2
return P
def da_k_a_fattore(N, a, t, k):
"""Classical post-processing: continued fraction, then gcd."""
r1 = Fraction(k, 2**t).limit_denominator(N).denominator
if pow(a, r1, N) != 1: # the denominator is not the period
return None, None
if r1 % 2 == 0 and pow(a, r1 // 2, N) != N - 1:
f = gcd(pow(a, r1 // 2, N) - 1, N)
if 1 < f < N:
return r1, (f, N // f)
return r1, None
for N, a, t in ((15, 7, 8), (21, 2, 10)):
r = next(r for r in range(1, N) if pow(a, r, N) == 1)
P = distribuzione(N, a, t)
Q = formula_chiusa(N, a, t, r)
ok = sum(P[k] for k in range(2**t) if da_k_a_fattore(N, a, t, k)[1])
print(f"N={N} a={a} r={r} t={t}: simulation and formula agree (< 1e-12): {bool(abs(P - Q).max() < 1e-12)}")
top = np.argsort(-P, kind="stable")[:r]
print(" peaks:", [(int(k), round(float(P[k]), 4)) for k in sorted(top)])
print(f" probability of obtaining the factors in one trial: {ok:.4f}")
rng = np.random.default_rng(7)
for k in rng.choice(2**t, size=4, p=P):
print(f" measurement k={k}: k/2^t={Fraction(int(k), 2**t)} -> (r, factors) = {da_k_a_fattore(N, a, t, int(k))}")
# Output:
# N=15 a=7 r=4 t=8: simulation and formula agree (< 1e-12): True
# peaks: [(0, 0.25), (64, 0.25), (128, 0.25), (192, 0.25)]
# probability of obtaining the factors in one trial: 0.5000
# measurement k=128: k/2^t=1/2 -> (r, factors) = (None, None)
# measurement k=192: k/2^t=3/4 -> (r, factors) = (4, (3, 5))
# measurement k=192: k/2^t=3/4 -> (r, factors) = (4, (3, 5))
# measurement k=0: k/2^t=0 -> (r, factors) = (None, None)
# N=21 a=2 r=6 t=10: simulation and formula agree (< 1e-12): True
# peaks: [(0, 0.1667), (171, 0.114), (341, 0.114), (512, 0.1667), (683, 0.114), (853, 0.114)]
# probability of obtaining the factors in one trial: 0.3222
# measurement k=512: k/2^t=1/2 -> (r, factors) = (None, None)
# measurement k=853: k/2^t=853/1024 -> (r, factors) = (6, (7, 3))
# measurement k=683: k/2^t=683/1024 -> (r, factors) = (None, None)
# measurement k=171: k/2^t=171/1024 -> (r, factors) = (6, (7, 3))
For N = 15 and a = 7 there are four peaks, at 0, 64, 128 and 192, each with probability 0.25: 4 divides 256, so the comb is perfect. Only s = 1 and s = 3 produce r = 4: s = 0 gives the fraction 0, which says nothing, and s = 2 gives 1/2, whose denominator 2 is not the order (7 squared is 4, not 1). So the probability of obtaining the factors in one trial is 0.5. The four fixed-seed measurements show the two outcomes: twice k = 192 with (3, 5), once k = 128 and once k = 0, without a result.
For N = 21, a = 2, t = 10 the period is 6, which does not divide 1024: the comb is not exact, the six largest peaks are worth 0.114 or 0.1667 and the rest of the probability spreads over the neighbouring values. Simulation and closed formula agree to within 10 to the power of minus 12; the probability of factoring in one trial drops to about 0.32.
Why 2n counting qubits are enough
The choice t = 2n (8 for 15, 10 for 21) makes the extraction reliable. The value k closest to the ideal peak is at a distance from s/r, after dividing by 2^t, of at most 1/(2·2^t); with 2^t ≥ N^2 it is at most 1/(2N^2). Two different fractions with denominator at most N are at least 1/N^2 apart, so no other fraction is as close: limit_denominator(N) returns exactly s/r, reduced to lowest terms.
"Reduced to lowest terms" is the detail to remember: if s and r have a common factor, the denominator read divides r without being equal to it, as for s = 2 above. The check pow(a, r1, N) != 1 discards these outcomes. There are variants that try the multiples of the denominator or combine two measurements; here I chose the simplest version so as not to hide the failure, which in the simulator is measured and on hardware is paid for in repetitions.
What the simulation hides
In the order listing the modular exponentiation is pow(a, x, N) for every x: a table built by a classical computer. On a real machine that table does not exist, it is a reversible modular-arithmetic circuit, and it is the dominant part of the cost. And the simulation requires memory exponential in n: the last line of the first listing (the one that enumerates the bases) showed that for 2048 bits you would need 2^6144 amplitudes.
For an order of magnitude of the real cost you need resource estimates. Gidney and Ekerå (article of 2019, revised in 2021) give in the abstract the cost in the abstract model, which ignores error correction and distillation: 3n + 0.002 n lg n logical qubits and 0.3 n^3 + 0.0005 n^3 lg n Toffoli gates for an RSA modulus of n bits. The listing applies those formulas to three values of n.
from math import log2
def stima_modello_astratto(n):
"""Formulas from the abstract of Gidney-Ekera 2019 (abstract model, n = bits of the modulus)."""
qubit_logici = 3 * n + 0.002 * n * log2(n)
toffoli = 0.3 * n**3 + 0.0005 * n**3 * log2(n)
return qubit_logici, toffoli
for n in (1024, 2048, 3072):
q, t = stima_modello_astratto(n)
print(f"n={n}: ~{q:,.0f} logical qubits, ~{t:.2e} Toffoli gates")
# Output:
# n=1024: ~3,092 logical qubits, ~3.27e+08 Toffoli gates
# n=2048: ~6,189 logical qubits, ~2.62e+09 Toffoli gates
# n=3072: ~9,287 logical qubits, ~8.87e+09 Toffoli gates
For 2048 bits the formulas give about 6,189 logical qubits and 2.6 billion Toffoli gates. They do not say how many physical qubits are needed: for that the authors add physical assumptions, namely a square lattice of superconducting qubits with nearest-neighbour interactions, a gate error of 10 to the power of minus 3, a surface-code cycle of 1 microsecond and a control reaction time of 10 microseconds. With those assumptions the 2019 estimate is 20 million noisy physical qubits for eight hours on a 2048-bit modulus.
In May 2025 Gidney published a new estimate, with the same assumptions: fewer than one million noisy physical qubits and less than a week. The drop in qubits comes from approximate residue arithmetic, from a more compact storage of idle qubits and from a cheaper distillation of magic states; the longer time from more Toffoli gates and fewer magic-state factories. They are estimates with declared assumptions, not demonstrations on a machine.
The real experiments are on tiny numbers. In 2001 a group factored 15 with seven nuclei in a molecule, using nuclear magnetic resonance, and stated in the same abstract that the work did not imply scalability. In 2012 a photonic experiment factored 21 with a "compiled" algorithm, that is with a circuit that already embeds information about the number to be factored. Smolin, Smith and Vargo then showed in 2013 that with a compiled circuit you can "factor" enormous products with only two coherent qubits, and concluded that the real difficulty is not the size of the number but the length of the period to be found. A compiled experiment on 15 or 21 therefore says nothing about scale.
What survives: post-quantum cryptography
Shor attacks problems with algebraic structure: factoring and the discrete logarithm. Both appear in its abstract. The NIST transition document, IR 8547 in the final version of October 2026, classifies RSA, ECDSA and EdDSA signatures and Diffie-Hellman and MQV key exchange as vulnerable to quantum computers (tables 2 and 4 of the document). Against symmetric encryption the known quantum attack is instead Grover's, covered in article 05, with only a quadratic advantage. On 13 August 2024 NIST published the first three post-quantum cryptography standards:
- FIPS 203, the key-encapsulation mechanism ML-KEM, used to agree on a secret key over a public channel;
- FIPS 204, the digital signature ML-DSA;
- FIPS 205, the digital signature SLH-DSA, based on hash functions and stateless.
The three acronyms cover the two uses that Shor threatens, key exchange and signature. The titles tell the family: lattices for the first two, hash functions for the third, that is problems different from factoring and the discrete logarithm. How they work inside is not explained here. On the calendar, IR 8547 states that NIST will deprecate quantum-vulnerable public-key cryptography after 2030 and disallow it in NIST standards and guidelines after 2035. For the most sensitive US federal systems the deadlines are tighter. For anyone designing software the practical lesson is simple: data that must stay secret for decades, encrypted today with a vulnerable mechanism, is already exposed to whoever records it now and waits for the machine.
What you can do now
You can reduce factoring to the computation of an order, and you can say with an example when the reduction fails. You can build the QFT as a circuit and compare it with the DFT, simulate the period-finding circuit on small moduli, extract the order with continued fractions and compute the success probability of one trial. You can also tell a compiled experiment from a general run of Shor, and read a resource estimate asking yourself which physical assumptions support it. The next step in the series leaves the algorithms with a theoretical advantage and moves to those that run on today's noisy machines: VQE for chemistry. The full list of chapters is on the series page.
Frequently asked questions
Can Shor's algorithm break RSA today?
No. The most recent resource estimates, with stated physical assumptions, speak of fewer than one million noisy physical qubits to factor a 2048-bit RSA modulus in less than a week. The published experiments have factored only tiny numbers such as 15 and 21.
Which part of Shor's algorithm is quantum?
Only the search for the period of a^x mod N, with modular exponentiation and the quantum Fourier transform. The choice of the base, the continued fractions and the computation of the greatest common divisor are classical and run on a laptop.
Which NIST standards replace RSA and ECC?
On 13 August 2024 NIST published FIPS 203 (ML-KEM, for agreeing on keys), FIPS 204 (ML-DSA) and FIPS 205 (SLH-DSA), the last two for digital signatures. The IR 8547 document plans to deprecate RSA, ECDSA and Diffie-Hellman after 2030 and to disallow them after 2035.
Later in the series you will also find quantum hardware (article 10).
Sources
- Shor, Polynomial-Time Algorithms for Prime Factorization and Discrete Logarithms on a Quantum Computer - the abstract, which states factoring and discrete logarithm in polynomial time on a hypothetical quantum computer (abstract read, SIAM J. Comput. 26, 1997 version, DOI 10.1137/S0097539795293172), consulted on 2026-11-13
- Gidney, Ekerå, How to factor 2048 bit RSA integers in 8 hours using 20 million noisy qubits - cost formulas in the abstract model, physical assumptions and the estimate of 20 million qubits in eight hours (abstract, version 3 of 13 April 2021), consulted on 2026-11-13
- Gidney, How to factor 2048 bit RSA integers with less than a million noisy qubits - the May 2025 estimate: fewer than one million qubits, less than a week, same assumptions (abstract), consulted on 2026-11-13
- Vandersypen et al., Experimental realization of Shor's quantum factoring algorithm using nuclear magnetic resonance - the factoring of 15 with seven nuclear spins and the caveat on scalability (abstract), consulted on 2026-11-13
- Martín-López et al., Experimental realisation of Shor's quantum factoring algorithm using qubit recycling - the factoring of 21 with a compiled algorithm on two photons (abstract), consulted on 2026-11-13
- Smolin, Smith, Vargo, Pretending to factor large numbers on a quantum computer - why the length of the period, not the size of the number, measures the difficulty (abstract), consulted on 2026-11-13
- NIST, FIPS 203: Module-Lattice-Based Key-Encapsulation Mechanism Standard - publication date 13 August 2024 and purpose of ML-KEM (page and abstract), consulted on 2026-11-13
- NIST, FIPS 204: Module-Lattice-Based Digital Signature Standard - date and purpose of ML-DSA (page and abstract), consulted on 2026-11-13
- NIST, FIPS 205: Stateless Hash-Based Digital Signature Standard - date and purpose of SLH-DSA (page and abstract), consulted on 2026-11-13
- NIST IR 8547, Transition to Post-Quantum Cryptography Standards - the tables of vulnerable algorithms and the calendar "deprecated after 2030, disallowed after 2035" (text read), consulted on 2026-11-13
- Python, fractions module - the
Fraction.limit_denominatormethod used for the continued fractions, consulted on 2026-11-13
The four listings in the article were run twice, with Python 3.14 and numpy 2.5, giving identical outputs: the outputs reported in the comments are the real ones. The resource estimates are calculations by the cited authors under their stated assumptions, not measurements on hardware.
Commenti
Caricamento commenti...
Sign in to comment