Shor's Algorithm

Break RSA encryption with quantum factorization

⏱️ 21 min8 interactions

1. What is Shor's Algorithm?

Shor's algorithm is the quantum algorithm that could break RSA encryption - the security protecting your bank accounts, passwords, and private communications. Discovered by Peter Shor in 1994, it can factor large numbers exponentially faster than any known classical algorithm, threatening the foundation of modern cryptography.

💡 Core Concept

RSA encryption relies on the fact that factoring large numbers is extremely hard for classical computers. A 2048-bit number would take billions of years to factor classically. Shor's algorithm uses quantum superposition and the Quantum Fourier Transform to find periods in modular arithmetic, reducing factoring from exponential to polynomial time - breaking RSA in hours instead of eons.

🔓 Why This Matters

When quantum computers become powerful enough to run Shor's algorithm on 2048-bit numbers, most of today's internet security will be broken. Banks, governments, and tech companies are racing to develop post-quantum cryptography before "Q-Day" arrives - the day quantum computers threaten global cybersecurity.

2. The Factoring Problem

🔐 Why Factoring Large Numbers Is Hard

The Asymmetry Problem

Factoring exhibits a profound computational asymmetry:

✅ Multiplication: EASY
61 × 89 = 5,429

Takes milliseconds, even for huge numbers (1000+ digits)

❌ Factoring: HARD
5,429 = ? × ?

Can take billions of years for large numbers (2048 bits)

Key insight: This asymmetry is a one-way function—easy in one direction, practically impossible in reverse. It's the foundation of modern cryptography!

How RSA Exploits This

RSA encryption relies on the difficulty of factoring:

Step 1: Choose Two Large Primes
p = (large prime), q = (large prime)

Example: 1024-bit primes (hundreds of digits each)

Step 2: Multiply Them (Easy!)
N = p × q (public key)

Takes microseconds even for 2048-bit numbers

Step 3: Security Relies on Factoring

N is public. If attacker can factor N = p × q, they break encryption. But classically, factoring takes longer than age of universe for 2048-bit N!

Real-world scale: RSA-2048 means N is a 2048-bit number (~617 digits). Current record for classical factoring: 829-bit number in 2020, took ~2700 CPU-years. 2048 bits? Infeasible!

Classical Factoring Algorithms

Best known classical approaches:

🐌 Trial Division (Naive)
Try dividing N by every number from 2 to √N
Time: O(√N)

For 2048-bit N: ~10^308 operations. Completely impractical.

⚡ General Number Field Sieve (Best)
Most sophisticated classical algorithm (1990s)
Time: O(exp(c · ∛(log N · log log N)²))

For 2048-bit N: ~2^117 operations. Still ~10^35 times longer than age of universe!

⚛️ Shor's Algorithm (Quantum)
Quantum algorithm using QFT and period finding
Time: O((log N)³)

For 2048-bit N: ~2^33 operations. Doable in hours on a large quantum computer!

Why Quantum Computers Break This

Classical Limitation

Must check possibilities sequentially or in limited parallelism. The search space grows exponentially with bit length. No amount of Moore's Law can overcome exponential growth.

Quantum Advantage: Superposition

Quantum computers can evaluate the function f(x) = a^x mod N for all x simultaneously using superposition. Instead of trying 2^2048 values sequentially, quantum superposition processes them in parallel.

Quantum Advantage: Interference

The Quantum Fourier Transform uses interference to extract the hidden period from the superposition. Wrong answers cancel (destructive interference), correct answer amplifies (constructive). This is impossible classically!

The paradigm shift: Shor's algorithm doesn't factor directly. It reduces factoring to period finding, which quantum computers can do exponentially faster through QFT. This clever reduction + quantum mechanics = RSA broken.

💣
The Cryptographic Crisis

RSA has protected internet security for 40+ years. Online banking, HTTPS, VPNs, code signing—all rely on factoring being hard. Shor's algorithm makes factoring polynomial instead of exponential, destroying this assumption. The difference is astronomical: what takes 10^35 years classically takes 8 hours quantumly. This isn't gradual progress—it's a catastrophic break. The entire edifice of public-key cryptography crumbles when large quantum computers arrive. That's why governments and corporations are urgently deploying post-quantum algorithms that don't rely on factoring. The race is on: deploy new crypto before quantum computers reach critical scale (~4,000 logical qubits needed for RSA-2048).

🔢 Interactive: Choose a Number to Factor

155391

Problem:

15 = ? × ?
Find the two prime factors

Computational Complexity:

Classical (Best Known):
0 steps
Exponential time: exp(√(log N × log log N))
Quantum (Shor's):
0 steps
Polynomial time: O((log N)³)
⚡ Speedup Factor:
Shor's algorithm is NaN× faster for N=15. For RSA-2048, the speedup is astronomical!

🎲 Interactive: Choose a Random Base

Step 1: Pick Random a (1 < a < N):

Selected Base:
7

Check GCD:

gcd(7, 15) = 1
✓ gcd = 1, proceed to quantum period finding
💡 Why Random?
Classical: Check if gcd(a, N) > 1 for quick factor. Quantum: Use superposition to test all bases simultaneously!

3. Quantum Period Finding

🔄 Period Finding: The Key to Factoring

What Is Period Finding?

Given a function f(x) = a^x mod N, find the period r—the smallest positive integer where:

a^r ≡ 1 (mod N)

Meaning: a^r mod N = 1, and r is the smallest such exponent

Example:
N=15, a=7 → 7^1=7, 7^2=49≡4, 7^3≡13, 7^4≡1 (mod 15) → period r=4

Why this matters: The function repeats every r steps. This periodicity is hidden in the exponents but reveals the factors of N!

How Period Leads to Factors

Once we find the period r, classical algebra extracts the factors:

Step 1: Use Period Property
a^r ≡ 1 (mod N)

This means: a^r - 1 is divisible by N

Step 2: Factor Difference of Squares (if r is even)
a^r - 1 = (a^(r/2) - 1)(a^(r/2) + 1)

Both factors share divisors with N!

Step 3: Compute GCD
p = gcd(a^(r/2) - 1, N), q = gcd(a^(r/2) + 1, N)

With high probability, p and q are non-trivial factors of N!

Concrete example: N=15, a=7, r=4 → a^(r/2)=7^2=49 → gcd(49-1, 15)=gcd(48,15)=3, gcd(49+1, 15)=gcd(50,15)=5 → 15 = 3 × 5 ✓

Why Classical Period Finding Is Hard

🐌 Brute Force Approach

Compute a^1, a^2, a^3, ... mod N until finding a^r = 1

• Must try up to N values (period could be N-1)
• For 2048-bit N: ~10^617 computations
• Each modular exponentiation is slow for large numbers
⚡ Fourier Analysis (Classical FFT)

Use Fast Fourier Transform to detect periodicity

• Still requires computing a^x mod N for all x
• Need 2^n samples for n-bit number
• Exponential time complexity: O(2^n)

The bottleneck: Classically, you must evaluate f(x) = a^x mod N for exponentially many x values. No clever classical algorithm can avoid this exponential cost.

Quantum Superposition: The Game Changer

Quantum computers solve period finding exponentially faster:

1. Quantum Superposition of Inputs

Use Hadamard gates to create superposition: |0⟩ + |1⟩ + |2⟩ + ... + |2^n-1⟩

All 2^n possible inputs exist simultaneously in one quantum state!
2. Quantum Modular Exponentiation

Apply f(x) = a^x mod N to the superposition

|x⟩|0⟩ → |x⟩|a^x mod N⟩
Evaluates function for all x simultaneously through quantum parallelism
3. Measure Second Register

Measuring |a^x mod N⟩ collapses to one value, say y

First register now contains superposition of all x where a^x ≡ y (mod N)
These x values are evenly spaced by the period r!
4. QFT Extracts Period

Quantum Fourier Transform reveals the spacing (period r)

Interference amplifies correct period, suppresses others
Measurement gives r with high probability

Time complexity: O((log N)³) quantum operations vs O(2^(log N)) = O(N) classical. For N=2^2048, this is 2^33 vs 2^2048 operations—astronomical difference!

Shor's Algorithm: The Complete Picture

1️⃣
Pick Random a (classical)

Choose 1 < a < N. Check if gcd(a, N) > 1 (lucky factor). Time: O(log N)

2️⃣
Find Period r (quantum)

Use quantum algorithm to find period of f(x) = a^x mod N. Time: O((log N)³)

3️⃣
Check if r is even and valid (classical)

If r is odd or a^(r/2) ≡ -1 (mod N), restart. Success probability: ~50%

4️⃣
Extract Factors (classical)

Compute p = gcd(a^(r/2)-1, N) and q = gcd(a^(r/2)+1, N). Time: O(log N)

Total time: O((log N)³) dominated by quantum period finding (step 2). Classical steps are negligible. Expected ~O(1) repetitions due to 50% success rate.

💎
The Elegant Reduction

Shor's brilliance wasn't just using quantum mechanics—it was reducing factoring to period finding, a problem where quantum computers have exponential advantage. The reduction is pure number theory (known for centuries), but period finding was classically hard. Quantum superposition + QFT makes period finding efficient, and the factoring reduction comes along for the ride. This clever transformation is why Shor's algorithm works: it exploits quantum interference patterns in modular arithmetic. The period is encoded in the phase relationships of the superposition, and QFT reads it out through measurement. Classical computers can't access these phase relationships—they're fundamentally quantum mechanical. That's the magic: math + quantum physics = broken cryptography.

🔄 Interactive: Run Shor's Algorithm

1
Initialize Quantum Registers
Prepare qubits in superposition
2
Quantum Modular Exponentiation
Compute 7^x mod 15 for all x simultaneously
3
Quantum Fourier Transform
Extract period from superposition
4
Classical Post-Processing
Calculate factors from period

🌊 Quantum Fourier Transform: Reading Quantum Interference

What Is the Quantum Fourier Transform?

The Quantum Fourier Transform (QFT) is the quantum analog of the discrete Fourier transform. It converts between two representations of a quantum state: the computational basis (position/time domain) and the Fourier basis (momentum/frequency domain). In Shor's algorithm, QFT extracts the hidden period from a quantum superposition by converting periodic patterns into sharp frequency peaks.

QFT vs Classical FFT

🖥️ Classical FFT
Transforms N classical values to frequency domain
• Input: N classical bits/numbers
• Output: N frequency coefficients
• Time: O(N log N)
• For n qubits: N = 2^n
• Must process 2^n values
⚛️ Quantum QFT
Transforms n-qubit superposition to Fourier basis
• Input: n qubits in superposition
• Output: n qubits in Fourier basis
• Time: O(n²) = O((log N)²)
• Works on superposition directly
• Exponentially faster!

Exponential speedup: For n=2048 qubits, classical FFT needs 2^2048 × 2048 ≈ 10^620 operations. QFT needs ~2048² ≈ 4 million operations. That's the quantum advantage!

How QFT Reveals the Period

After quantum modular exponentiation, the state contains periodic structure:

Before QFT: Time Domain
|ψ⟩ = |x₀⟩ + |x₀+r⟩ + |x₀+2r⟩ + |x₀+3r⟩ + ...

Superposition of states evenly spaced by period r. The period is implicit in the spacing between non-zero amplitudes.

↓ Apply QFT
After QFT: Frequency Domain
|ψ'⟩ = |0⟩ + |N/r⟩ + |2N/r⟩ + |3N/r⟩ + ...

Peaks appear at multiples of N/r. The period r is explicit in the peak spacing! Measuring gives k×(N/r) for some integer k, from which we extract r.

Mathematical magic: Time-domain periodicity with spacing r transforms to frequency-domain peaks with spacing N/r. This is the discrete Fourier transform duality—QFT exploits quantum interference to compute it efficiently!

The Circuit Implementation

QFT Circuit Structure

For n qubits, QFT uses Hadamard gates + controlled phase rotations:

1. Apply Hadamard to qubit 1
2. Apply controlled-R₂ from qubit 2 to qubit 1
3. Apply controlled-R₃ from qubit 3 to qubit 1
... (n-1 controlled rotations for qubit 1)
4. Repeat for qubit 2 with (n-2) rotations
5. Continue until last qubit (just Hadamard)
Gate Count
• Total gates: n Hadamards + n(n-1)/2 controlled rotations
• Complexity: O(n²) gates for n qubits
• Compare to classical FFT: O(2^n × n) operations
• For n=2048: ~4M gates vs ~10^620 operations!

Controlled phase gates: R_k = diag(1, e^(2πi/2^k)) adds phase based on qubit position. These phases encode the Fourier transform—quantum interference does the heavy lifting!

Why QFT Is Essential for Shor's

🔍 Extracts Hidden Information

The period is hidden in the phase relationships of the superposition. Direct measurement would just give random x values. QFT rotates to the basis where period is observable as frequency peaks.

🌊 Uses Quantum Interference

Multiple quantum paths interfere constructively at frequencies that are multiples of N/r, and destructively elsewhere. This selective amplification is impossible classically—it requires quantum phase coherence.

⚡ Achieves Exponential Speedup

Without QFT, we'd need to measure the superposition many times and classically analyze the pattern—exponential time. QFT does it in one shot with O(n²) gates by processing the entire superposition coherently.

Measurement & Post-Processing

After QFT, measurement collapses to a peak value:

1.
Measure QFT output: get integer k×(N/r) for unknown integer k
2.
Divide by N: get fraction k/r (reduced to lowest terms)
3.
Use continued fractions algorithm to find r from k/r
4.
Verify: check if a^r ≡ 1 (mod N). If not, repeat measurement

Success probability: Single measurement has ~40% chance of yielding correct r. Usually need 2-3 measurements. Still polynomial time overall!

🎯
The Heart of Quantum Advantage

QFT is where Shor's algorithm becomes truly quantum. Everything before (superposition, modular exponentiation) prepares a state with periodic structure. But QFT is what reads that structure out exponentially faster than any classical method. It exploits quantum interference at a massive scale—2^n paths interfering coherently to amplify the period signal. Classical computers must sample these paths sequentially (exponential time). Quantum computers process them in parallel through superposition, then use constructive/destructive interference via QFT to extract the answer (polynomial time). This is the essence of quantum computing: use interference to solve problems where classical approaches drown in exponentially large spaces. QFT isn't just faster—it's fundamentally different, accessing information encoded in quantum phases that have no classical analog.

🌊 Interactive: Quantum Fourier Transform

How QFT Works:

1. Creates quantum superposition of all inputs
2. Transforms to frequency domain
3. Peaks appear at multiples of 1/period
4. Measurement reveals the period
⚡ The Magic:
QFT converts time-domain periodicity into frequency-domain peaks, making the hidden period obvious through quantum interference!

Time Domain (Before QFT)

Equal amplitudes across all states

4. Breaking RSA Encryption

🔐 Interactive: RSA Key Sizes

256102420484096
⏱️ Classical Factoring Time:
Days
Best classical algorithms
⚛️ Quantum Factoring Time:
Seconds
Shor's algorithm (when quantum computers scale)
⚠️ Security Status:
Already broken by classical computers!

🏁 Interactive: The Factoring Race

Progress factoring RSA-2048:0.00001%
⏱️ Estimated time: 6.4 quadrillion years
💻 Hardware: Supercomputer cluster
📊 Method: General Number Field Sieve
*The universe is only 13.8 billion years old

🔬 Interactive: Quantum Resources Needed

80128192256
Logical Qubits Needed:
256
Physical Qubits (est.):
256,000
Gate Operations:
~2,097,152
📊 Current State of Quantum Computers:
IBM Quantum (2024):~1,000 qubits (noisy)
Google Sycamore:~70 qubits
Needed for RSA-2048:~4,000 logical qubits
With error correction:~4,000,000 physical qubits
We're still years away from breaking RSA-2048, but progress is accelerating!

5. Key Takeaways

Exponential Speedup

Shor's algorithm solves integer factorization in polynomial time O((log N)³), compared to exponential time for classical algorithms. This is one of the most dramatic quantum advantages known.

🌊

Quantum Fourier Transform

The QFT is the quantum analog of the classical Fast Fourier Transform, but exponentially faster. It's the key ingredient that enables Shor's algorithm to extract periods from quantum superpositions.

🔓

Threat to Cryptography

RSA, Diffie-Hellman, and elliptic curve cryptography will all be broken by Shor's algorithm. The race is on to deploy post-quantum cryptography before large-scale quantum computers arrive.

🔬

Still Years Away

Breaking RSA-2048 requires ~4 million error-corrected qubits. Today's quantum computers have ~1,000 noisy qubits. But progress is rapid - some estimate Q-Day could arrive by 2030-2035.

🛡️

Post-Quantum Solutions

NIST has standardized post-quantum algorithms (lattice-based, hash-based, code-based) that are believed to be secure against quantum attacks. Migration is already beginning.

🚀

Beyond Factoring

Shor's algorithm also solves the discrete logarithm problem and can be adapted for other cryptographic systems. It showcases the true power of quantum computing for specific problems.