🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Shor's Algorithm

Quantum ComputingShor's AlgorithmđŸŸĸ Free Lesson

Overview

Shor's algorithm (1994) factors an integer in time, compared to the best-known classical algorithm (general number field sieve) which runs in sub-exponential time .

The algorithm combines classical number theory with the quantum Fourier transform to find the period of a modular exponential function.

Reduction to Period Finding

Shor's insight is that factoring reduces to period finding. Choose a random with . Define:

This function is periodic with some period (the order of modulo ). If is even, then:

With probability , gives a non-trivial factor of .

A Worked Example: Factoring 15 and 21

Follow the reduction by hand on two composites small enough to check. For pick : successive powers are , so the order is . That is even, and , so and . The factorisation falls out of one period.

For pick : the powers run , giving . Now , and , , so . Both examples also show the branches that force a retry: if comes out odd — as it does for modulo 21, where the powers run and the run dies — or if is congruent to modulo , the base is discarded and a fresh one is drawn.

Powers of mod Factor pair
1577, 4, 13, 144gcd(3, 15) = 3 and gcd(5, 15) = 5
2122, 4, 8, 16, 11, 168gcd(7, 21) = 7 and gcd(9, 21) = 3
1544, 124gcd(3, 15) = 3 immediately

Quantum Period Finding

The quantum circuit for period finding:

  1. Prepare two registers: with and
  2. Apply Hadamard to the first register:
  3. Compute into the second register
  4. Apply the Quantum Fourier Transform to the first register
  5. Measure the first register to obtain a value close to for some integer
  6. Use the continued fractions algorithm classically to extract

Register Size and Continued Fractions

The measurement does not return directly. It returns an integer in that approximates for an unknown , and the classical task is to turn the fraction into . Continued fractions do this by taking the convergents of in order: each convergent satisfies , and Legendre's theorem says a fraction meeting that bound is a convergent of the continued fraction. Because is within of , the denominator appears as a convergent provided .

That inequality sets the register width. Since , the safe choice is qubits in the first register; a tighter design sizes to the expected order and accepts a few retries. An that is too narrow makes two different fractions collide into the same measured , and continued fractions then dutifully returns a denominator that divides rather than itself — a recoverable failure, because you can combine denominators from several runs by taking their greatest common divisor.

When a Run Fails: Retry Logic

Three classical outcomes end a run without a factor. An odd gives no split at all. makes both candidate gcds trivial. And the recovered denominator can be a proper divisor of , in which case the extracted value is not the period but a factor of it. Each is handled by the same response: draw a new random base coprime to and run again.

The probabilities work out in the algorithm's favour. With having at least two distinct odd prime factors, at least half the bases coprime to produce an even with , so two or three attempts suffice on average rather than the quadratic many a pessimistic reading suggests. The classical parts — gcd, exponentiation, continued fractions — all run in bit operations, which is why the quantum subroutine is the only piece that needs the speedup.

Modular Exponentiation

The quantum circuit for computing uses gates via repeated squaring:

Each modular multiplication can be implemented using gates with quantum arithmetic circuits.

This is the bottleneck of Shor's algorithm — it requires quantum gates, which is why factoring large numbers requires fault-tolerant quantum computers.

Complexity Analysis

The overall complexity of Shor's algorithm:

StepClassicalQuantum
Random a selectionO(log N)—
Period findingO(2^n/2)O(n^3)
Continued fractionsO(n^3)—
GCD computationO(n^3)—

Total quantum gates: .

For a 2048-bit RSA key, this requires approximately quantum gates — well beyond current hardware but feasible with future fault-tolerant devices.

Python: Classical Order Finding

python
import numpy as np
from math import gcd

def find_order(a, N):
    # Classical order finding: find smallest r such that a^r = 1 (mod N).
    if gcd(a, N) != 1:
        return None
    r = 1
    current = a % N
    while current != 1:
        current = (current * a) % N
        r += 1
        if r > N:
            return None
    return r

def shor_factor(N):
    # Attempt to factor N using Shor's algorithm (classical simulation).
    from random import randint
    a = randint(2, N - 1)
    if gcd(a, N) != 1:
        return gcd(a, N), N // gcd(a, N)
    r = find_order(a, N)
    if r is None or r % 2 == 1:
        return None
    x = pow(a, r // 2, N)
    if x == N - 1:
        return None
    p = gcd(x + 1, N)
    q = gcd(x - 1, N)
    if p * q == N and p != 1 and q != 1:
        return p, q
    return None

result = shor_factor(21)
print(f"Factors of 21: {result}")

This demonstrates the classical post-processing of Shor's algorithm.

Python: Continued-Fraction Extraction

The half of the algorithm that never touches a quantum device is the half people skip, so it is worth seeing in full — ideal QPE outcomes going in, denominators coming out:

python
import numpy as np
from fractions import Fraction
from math import gcd

def order(a, N):
    r, cur = 1, a % N
    while cur != 1:
        cur = cur * a % N
        r += 1
        if r > N:
            return None
    return r

def qpe_outcome(a, N, n_bits, rng):
    """Ideal QPE measurement: y approximates k * 2^n / r."""
    r = order(a, N)
    if r is None:
        return None, None
    coprime = [k for k in range(1, r) if gcd(k, r) == 1] or [1]
    k = int(rng.choice(coprime))
    return int(round(k * (1 << n_bits) / r)), r

def from_outcome(y, n_bits, N):
    """Continued fractions: turn y / 2^n into a denominator."""
    return Fraction(y, 1 << n_bits).limit_denominator(N).denominator

rng = np.random.default_rng(0)
for a, N in [(7, 15), (2, 21), (4, 15), (5, 21), (11, 15)]:
    n_bits = 8
    y, r_true = qpe_outcome(a, N, n_bits, rng)
    r_est = from_outcome(y, n_bits, N)
    note = "matches" if r_est == r_true else f"divides r ({r_est}), gcd across runs"
    print(f"a={a:2d}  N={N:2d}  r={r_true}  y={y:3d}  extracted r={r_est}  {note}")

Five bases, five correct denominators, all with only 8 bits in the measurement register: comfortably exceeds for the largest period in the set. Raise the modulus to a 2048-bit RSA number and the same eight lines still run in milliseconds — the extraction step never becomes the bottleneck. What changes is , which has to clear before the convergents stop colliding.

Quantum Fourier Transform in Shor's

The QFT on qubits maps:

For Shor's algorithm, the QFT extracts the period from the superposition created by modular exponentiation. The QFT circuit uses gates: Hadamard gates and controlled phase rotations.

The inverse QFT (used in QPE) has the conjugate transformation and is used to decode the phase information.

Practical Considerations

For real-world factoring with Shor's algorithm:

  1. RSA-2048: requires about 4000 logical qubits and roughly T-gates
  2. Error correction overhead: around 1000 physical qubits per logical qubit
  3. Total: on the order of 4 million physical qubits
  4. Timeline: estimates cluster around 10 to 20 years for fault-tolerant hardware of that scale

Post-quantum migration should begin now to protect data with long-term sensitivity.

Common Mistakes

Treating a measured value as the period directly

Fix: Run continued fractions on the measured fraction, then verify the candidate with fast modular exponentiation before using it

Giving up when the extracted denominator divides the true period

Fix: Combine denominators from several runs by taking their greatest common divisor, which recovers the full period

Skipping the classical checks before accepting a period

Fix: Test that r is even and that a raised to r over two is not minus one modulo N; both failures give trivial gcds, so redraw the base instead of paying for another quantum run

Budgeting for Shor in linear gate count

Fix: Modular exponentiation dominates at cubic depth in the bit width, which is why factoring waits for error correction while chemistry does not

Key Takeaways

  • Shor reduces factoring to finding the order of a random base modulo N, then splits N with a gcd once that order is even
  • The measurement register needs more than twice log base two of r bits, because continued fractions only isolates the period when 2 to the n exceeds r squared
  • Each attempt succeeds with probability at least one half, so two or three random bases cover a typical factoring run
  • The bottleneck is modular exponentiation at cubic gate count, putting RSA-2048 factoring at roughly four million physical qubits
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-15

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Quantum Computing Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement