Shor's Factoring Algorithm
The algorithm that put quantum computing on the map
π₯ Why Shor's Algorithm Changed Everything
In 1994, Peter Shor proved that quantum computers could break RSA encryptionβthe system protecting most of the internet. This single result made governments and companies pour billions into quantum computing research.
Classical Factoring
Best known: General Number Field Sieve (GNFS)
β±οΈ exp(O(n^1/3)) time
For 2048-bit RSA β billions of years
Shor's Algorithm
Quantum Fourier Transform + period finding
β‘ O(nΒ³) time
For 2048-bit RSA β hours (with future quantum computers)
β The Problem: Integer Factorization
Given: A large number N (e.g., 15, 21, 391, or 2048-bit RSA modulus)
Goal: Find prime factors p and q such that N = p Γ q
Why Is This Hard?
Multiplication is Easy
1223 Γ 1987 = 2,430,101
β Instant
Factoring is Hard
2,430,101 = ?
β±οΈ Must try many candidates
This asymmetry is what makes RSA encryption secure. You can multiply two primes easily (to create a public key), but factoring the result (to break it) is computationally infeasible.
βοΈ How Shor's Algorithm Works (High Level)
Shor's algorithm doesn't directly factor N. Instead, it uses a clever mathematical trick:
The Key Insight: Period Finding
Factoring reduces to finding the period of a modular function.
- Pick a random number a (coprime to N)
-
Find the period r of the function:
f(x) = aΛ£ mod NThe period r is the smallest integer where f(x+r) = f(x) for all x
-
Use r to find factors:
p = gcd(a^(r/2) - 1, N) q = gcd(a^(r/2) + 1, N)If r is even and a^(r/2) β -1 mod N, these give non-trivial factors
π’ Step-by-Step Algorithm
Classical Preprocessing (Steps 1-2)
- Check if N is even: If yes, factor is 2 (trivial). Done.
- Check if N = a^b for some integers a, b: If yes, use classical methods. Done.
- Pick random a between 2 and N-1
- Compute gcd(a, N): If gcd > 1, you found a factor. Done.
Quantum Period Finding (Steps 3-5)
-
Initialize quantum registers:
Register 1: n qubits in |0β© (for x values) Register 2: n qubits in |0β© (for f(x) = aΛ£ mod N) -
Apply Hadamard to Register 1: Create superposition
|Οβ© = (1/β2βΏ) Ξ£β |xβ©|0β© -
Compute f(x) in superposition:
|Οβ© = (1/β2βΏ) Ξ£β |xβ©|aΛ£ mod Nβ©This is done using modular exponentiation circuits (hardest part to implement)
-
Measure Register 2: Collapses to some result yβ
Now Register 1 is left in a state containing all x values where f(x) = yβ. These x values are separated by the period r.
-
Apply Quantum Fourier Transform (QFT) to Register 1:
QFT converts the periodic state into peaks at multiples of 2βΏ/r - Measure Register 1: Get a value close to kΒ·2βΏ/r for some integer k
- Extract the period r: Use continued fractions to find r from the measurement
Classical Postprocessing (Step 6)
- Check if r is even and a^(r/2) β -1 mod N: If not, go back to step 3 (pick new a)
-
Compute factors:
p = gcd(a^(r/2) - 1, N) q = gcd(a^(r/2) + 1, N) - Verify: Check if p and q are non-trivial factors. Done!
π Example: Factoring N = 15
Let's factor 15 using Shor's algorithm:
Step 1-4: Classical Preprocessing
- N = 15 is odd β not divisible by 2
- 15 β a^b for any integers β proceed
- Pick a = 7 (random choice between 2 and 14)
- gcd(7, 15) = 1 β proceed to quantum part
Step 5-11: Quantum Period Finding
We need to find the period r of f(x) = 7^x mod 15:
| x | 7^x mod 15 |
|---|---|
| 0 | 1 |
| 1 | 7 |
| 2 | 4 |
| 3 | 13 |
| 4 | 1 β repeats! |
| 5 | 7 |
| 6 | 4 |
Period r = 4 (the function repeats every 4 steps)
The quantum computer finds this using QFT, not by computing the table!
Step 12-14: Classical Postprocessing
- r = 4 is even β
- a^(r/2) = 7Β² = 49 mod 15 = 4 β -1 β
- Compute factors:
p = gcd(7Β² - 1, 15) = gcd(48, 15) = 3 q = gcd(7Β² + 1, 15) = gcd(50, 15) = 5 - Result: 15 = 3 Γ 5 β
π The Quantum Fourier Transform (QFT)
The QFT is the heart of Shor's algorithm. It's the quantum version of the classical Fast Fourier Transform (FFT).
What It Does
The QFT transforms a quantum state from the computational basis to the frequency basis:
QFT |xβ© = (1/βN) Ξ£β e^(2Οixk/N) |kβ©
Why It Matters for Period Finding
If you have a periodic state (like the one after measuring Register 2), the QFT concentrates amplitude at frequencies corresponding to the period.
Intuition: Listening to Music
π΅ You hear a sound wave (time domain)
π FFT converts it to frequencies (which notes are playing)
π― QFT does the same for quantum statesβfinds the "frequency" (period) hidden in the superposition
Complexity Advantage
Classical FFT
O(N log N) operations
For N = 2^2048 β impractical
Quantum QFT
O(nΒ²) gates (n = log N)
For N = 2^2048 β ~4 million gates
π» Implement It (Qiskit)
Full implementation of Shor's algorithm is complex (~500 lines). Here's a simplified version using Qiskit's built-in Shor function:
from qiskit.algorithms import Shor
from qiskit.utils import QuantumInstance
from qiskit import Aer
# Number to factor
N = 15
# Create a Shor instance
shor = Shor()
# Use the simulator backend
backend = Aer.get_backend('aer_simulator')
quantum_instance = QuantumInstance(backend, shots=1024)
# Run Shor's algorithm
result = shor.factor(N, quantum_instance=quantum_instance)
print(f"Factoring N = {N}")
print(f"Factors: {result.factors}")
print(f"Successful factorization: {N} = {result.factors[0][0]} Γ {result.factors[0][1]}")
# Output:
# Factoring N = 15
# Factors: [(3, 5)]
# Successful factorization: 15 = 3 Γ 5
Building QFT from Scratch (Educational)
from qiskit import QuantumCircuit
import numpy as np
def qft(circuit, qubits):
"""Apply Quantum Fourier Transform to qubits."""
n = len(qubits)
for i in range(n):
# Apply Hadamard
circuit.h(qubits[i])
# Apply controlled phase rotations
for j in range(i + 1, n):
angle = 2 * np.pi / (2 ** (j - i + 1))
circuit.cp(angle, qubits[j], qubits[i])
# Reverse the order (optional, depends on convention)
for i in range(n // 2):
circuit.swap(qubits[i], qubits[n - i - 1])
# Example: 3-qubit QFT
qc = QuantumCircuit(3)
qft(qc, [0, 1, 2])
print(qc)
Shor class for real experiments.
π Real-World Impact
What's at Risk
RSA Encryption
Used by: HTTPS, VPNs, SSH, PGP email
π‘οΈ β π₯ Broken by Shor's
Elliptic Curve Crypto (ECC)
Used by: Bitcoin, SSL certificates
π‘οΈ β π₯ Also broken
Diffie-Hellman Key Exchange
Used by: TLS, Signal, WhatsApp
π‘οΈ β π₯ Broken
What's Safe (Post-Quantum Cryptography)
- Lattice-based crypto (NTRU, Kyber) β no known quantum attack
- Hash-based signatures (SPHINCS+) β quantum-resistant
- Code-based crypto (McEliece) β safe from Shor's
Timeline Estimate
- Current quantum computers: ~1,000 qubits (not enough, too noisy)
- Needed for RSA-2048: ~4,000 logical qubits (= ~1 million physical qubits with error correction)
- Optimistic timeline: 10-15 years
- Realistic timeline: 20-30 years
Action needed now: Organizations with long-term secrets (governments, healthcare, finance) must migrate to post-quantum crypto today because of "harvest now, decrypt later" attacks.
β οΈ Common Mistakes
β Mistake 1: "Shor's algorithm directly factors numbers"
Wrong. It finds the period of a modular function, then uses classical math to extract factors.
β Mistake 2: "Quantum computers break all encryption"
Wrong. Only public-key crypto (RSA, ECC) is broken.
AES-256 (symmetric) remains secure (Grover's only provides quadratic speedup β use AES-256 instead of AES-128).
β Mistake 3: "Shor's algorithm works on any large number"
Catch: It requires error-corrected qubits. Current quantum computers lack the qubit count and coherence time.
Largest number factored by Shor's to date: 21 = 3 Γ 7 (in 2012, using simplifications)
π οΈ Practice Exercises
Exercise 1: Period Finding by Hand
Task: Find the period of f(x) = 2^x mod 21.
Show Solution
Compute: 2^0 = 1, 2^1 = 2, 2^2 = 4, 2^3 = 8, 2^4 = 16, 2^5 = 11, 2^6 = 1 (mod 21)
Period r = 6
Exercise 2: Extract Factors
Given: N = 21, a = 2, r = 6. Find the factors.
Show Solution
p = gcd(2^(6/2) - 1, 21) = gcd(8 - 1, 21) = gcd(7, 21) = 7
q = gcd(2^(6/2) + 1, 21) = gcd(8 + 1, 21) = gcd(9, 21) = 3
Result: 21 = 3 Γ 7 β
Exercise 3: Run Shor's in Qiskit
Task: Factor N = 21 using Qiskit's Shor implementation.
Show Solution
from qiskit.algorithms import Shor
from qiskit.utils import QuantumInstance
from qiskit import Aer
N = 21
shor = Shor()
backend = Aer.get_backend('aer_simulator')
quantum_instance = QuantumInstance(backend, shots=1024)
result = shor.factor(N, quantum_instance=quantum_instance)
print(f"21 = {result.factors[0][0]} Γ {result.factors[0][1]}")
π What's Next?
You've learned:
- β Why Shor's algorithm is revolutionary (exponential speedup)
- β How period finding leads to factoring
- β The role of QFT in extracting periodicity
- β Real-world implications for cryptography
π You've Completed Phase 2!
You now understand the three most important quantum algorithms:
- Deutsch-Jozsa: Foundational techniques (interference, oracles)
- Grover's Search: Practical speedup for unstructured search
- Shor's Factoring: Exponential advantage, cryptographic impact
Next step: See the Success Criteria to assess your readiness for Phase 3.