Phase 2.3

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)

This Is Exponential Speedup: Not just 1000Γ—, but fundamentally different complexity classes. Classical: exponential time. Quantum: polynomial time.

❓ 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.

Why RSA Dies When Quantum Arrives: Shor's algorithm breaks this asymmetry. Once large quantum computers exist (~4000 qubits), current RSA/ECC encryption becomes useless.

βš›οΈ 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.

  1. Pick a random number a (coprime to N)
  2. Find the period r of the function:
    f(x) = aΛ£ mod N

    The period r is the smallest integer where f(x+r) = f(x) for all x

  3. 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

Why Quantum Helps: Finding the period r classically requires exponential time. Quantum computers can find it in polynomial time using the Quantum Fourier Transform (QFT).

πŸ”’ Step-by-Step Algorithm

Classical Preprocessing (Steps 1-2)

  1. Check if N is even: If yes, factor is 2 (trivial). Done.
  2. Check if N = a^b for some integers a, b: If yes, use classical methods. Done.
  3. Pick random a between 2 and N-1
  4. Compute gcd(a, N): If gcd > 1, you found a factor. Done.

Quantum Period Finding (Steps 3-5)

  1. Initialize quantum registers:
    Register 1: n qubits in |0⟩  (for x values)
    Register 2: n qubits in |0⟩  (for f(x) = aˣ mod N)
  2. Apply Hadamard to Register 1: Create superposition
    |ψ⟩ = (1/√2ⁿ) Ξ£β‚“ |x⟩|0⟩
  3. Compute f(x) in superposition:
    |ψ⟩ = (1/√2ⁿ) Ξ£β‚“ |x⟩|aΛ£ mod N⟩

    This is done using modular exponentiation circuits (hardest part to implement)

  4. 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.

  5. Apply Quantum Fourier Transform (QFT) to Register 1:
    QFT converts the periodic state into peaks at multiples of 2ⁿ/r
  6. Measure Register 1: Get a value close to k·2ⁿ/r for some integer k
  7. Extract the period r: Use continued fractions to find r from the measurement

Classical Postprocessing (Step 6)

  1. Check if r is even and a^(r/2) β‰  -1 mod N: If not, go back to step 3 (pick new a)
  2. Compute factors:
    p = gcd(a^(r/2) - 1, N)
    q = gcd(a^(r/2) + 1, N)
  3. 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
01
17
24
313
41 ← repeats!
57
64

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)
Note: Implementing full Shor's algorithm requires modular exponentiation circuits, which are very complex. Use Qiskit's built-in 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
Current Status: NIST standardized post-quantum algorithms in 2024. Migration is underway, but billions of devices still use vulnerable RSA/ECC.

Timeline Estimate

When Will Quantum Computers Break RSA?
  • 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.