← Back to Home

🧩 P vs NP

Some problems are easy to check but seem very hard to solve. Internet security depends on that gap. This tutorial covers what P and NP mean, why nobody has proved them different, and what would happen to HTTPS, banking and Bitcoin if P = NP.

1. Fast vs Slow: How We Measure "Hard"

Computer scientists don't call a problem "hard" because it takes long on today's laptop. They ask a different question: as the input grows, how quickly does the work grow?

📈 Drag the slider: how many steps for input size n?

The time estimates assume a computer doing 1 billion steps per second. Bars use a log scale; each grid step is 1000× more work.

💡 Why this matters: at n = 80, n³ is half a millisecond, while 2ⁿ is about 38 million years. Buying a faster computer doesn't close that gap. You need a better algorithm, and for some problems nobody knows whether one exists.

2. P: Problems We Can Solve Fast

P (Polynomial time) is the class of yes/no problems that a normal computer can solve in polynomial time. You use these every day without thinking about it:

ProblemEveryday exampleAlgorithmCost
SortingOrder your inbox by dateMerge sortn log n
Searching a sorted listLook up a word in a dictionaryBinary searchlog n
Shortest pathGoogle Maps: home → officeDijkstra(V+E) log V
MultiplicationMultiply two 600-digit numbersSchoolbook / Karatsuban² / n^1.58
Is this number prime?Generate a key for RSAAKS (2002), Miller–Rabin in practicepolynomial in digits
MatchingAssign interns to teams by preferenceGale–Shapleyn²
⚠️ Two problems that look alike: "Is 221 prime?" is in P. We can answer it fast even for numbers with thousands of digits. "What are the prime factors of 221?" (13 × 17) has no known fast algorithm for large numbers. RSA encryption depends on that difference.

3. NP: Problems We Can Check Fast

NP (Nondeterministic Polynomial time) is the class of yes/no problems where, if the answer is "yes", someone can hand you a proof (called a certificate or witness) that you can verify in polynomial time.

A good mental model is a jigsaw puzzle. Assembling a 5,000-piece puzzle takes days. Checking that a finished puzzle is correct takes a glance.

Here is a classic NP problem called Subset Sum: given a list of numbers, is there a subset that adds up exactly to a target? Try it.

🎯 Subset Sum: find numbers that add up to ?

Click numbers to select them. The check is instant: it's just one addition.

Notice the asymmetry:

# subset_sum.py: verifying is fast, solving (naively) is exponential
from itertools import combinations

def verify(numbers, target, certificate):
    """O(n): is the proposed subset valid and does it hit the target?"""
    return all(x in numbers for x in certificate) and sum(certificate) == target

def solve_brute_force(numbers, target):
    """O(2^n): try every possible subset."""
    for size in range(len(numbers) + 1):
        for subset in combinations(numbers, size):
            if sum(subset) == target:
                return list(subset)
    return None

nums = [3, 34, 4, 12, 5, 2]
print(verify(nums, 9, [4, 5]))        # True, checked instantly
print(solve_brute_force(nums, 9))     # [4, 5], found by searching
💡 Every P problem is also in NP. If you can solve a problem fast, you can verify an answer fast by solving it yourself and comparing. So P ⊆ NP. The open question is whether the two classes are actually the same.

4. The Million-Dollar Question

Stephen Cook stated the question formally in 1971, and Leonid Levin reached the same result independently in the USSR:

If a solution can be verified quickly, can it always be found quickly?

World 1: P ≠ NP most experts believe this

NP
P
NP-complete

Some problems really are harder to solve than to check. Creativity can't be automated away, and cryptography can be secure.

World 2: P = NP would upend computing

P = NP = NP-complete

Any puzzle whose answer you can recognize, you can also solve efficiently. The gap that cryptography depends on is gone.

It is one of the seven Clay Millennium Prize Problems, with a $1,000,000 reward for a proof either way. More than 50 years later it remains unsolved. In surveys, most researchers say they believe P ≠ NP, but nobody has proved it.

5. NP-Complete: The Hardest Problems in NP

In 1971 Cook (and independently Levin) proved something surprising. One NP problem, Boolean Satisfiability (SAT), is at least as hard as every other NP problem. Any NP problem can be translated (reduced) into a SAT question in polynomial time.

In 1972 Richard Karp showed that 21 more classic problems have the same property. Today thousands are known. These problems are called NP-complete.

Sudoku (n×n generalized)
⇄
SAT logic puzzles
⇄
Traveling Salesman (decision version)
⇄
Graph Coloring exam scheduling
NP-complete problemPlain EnglishWhere it shows up
SAT / 3-SATCan these true/false variables be set so every rule holds?Chip verification, package dependency resolvers
Traveling Salesman (decision)Is there a tour of all cities shorter than k km?Delivery routes, PCB drilling
Graph ColoringCan you color the map with 3 colors so no neighbors match?Exam timetables, CPU register allocation
Knapsack / Subset SumBest set of items under a weight limit?Budgeting, cargo loading
Generalized SudokuFill an n²×n² grid so the rules holdPuzzles (and a great teaching example)
💡 One key opens every lock: since every NP problem reduces to any NP-complete problem, a fast algorithm for just one of them (Sudoku, say) would give a fast algorithm for all of NP. That would prove P = NP.

6. One-Way Functions: Easy Forward, Hard Backward

Cryptography needs a one-way function: something easy to compute but hard to reverse. A familiar comparison is mixing paint. Mixing blue and yellow into green is easy, while separating green back into blue and yellow is close to impossible.

The best-known example is multiplying two primes. Multiplying is in P. Reversing it means factoring, and the best known methods are dramatically slower. Try it below. The factoring uses simple trial division running in your browser.

⚔️ Multiply vs Factor race

➡️ Forward: p × q
Press Run race.
⬅️ Backward: find p, q from n
Waiting…

Each extra bit in the primes makes trial division about 1.4× slower. Real RSA uses 1024-bit primes.

One-way functionEasy directionHard directionUsed by
Integer factorizationMultiply p × qFactor nRSA
Discrete logarithmCompute gˣ mod pRecover xDiffie–Hellman, DSA
Elliptic-curve discrete logCompute k · G on a curveRecover kECDHE (X25519), ECDSA, Ed25519, Bitcoin
Cryptographic hashSHA-256(x)Find x from the hashPasswords, Git, TLS, blockchains
Lattice problems (LWE)Compute A·s + eRecover sML-KEM / Kyber (post-quantum TLS)
💡 The link to P vs NP: every "hard direction" in that table is an NP problem. If someone hands you p and q, you can check p × q = n instantly. A one-way function can only exist if P ≠ NP. If P = NP, nothing can be easy forward and hard backward.

7. Toy RSA: Encrypt, Decrypt, Crack

RSA (1977) is the classic public-key system. Anyone can encrypt with your public key (n, e), but only you can decrypt, because only you know the factors of n.

  1. Pick two secret primes p, q. Compute n = p × q and φ = (p−1)(q−1).
  2. Pick a public exponent e (usually 65537). Compute the private key d = e⁻¹ mod φ.
  3. Encrypt: c = mᵉ mod n. Decrypt: m = cᵈ mod n.

The attacker sees n and e. To compute d they need φ, and to get φ they need to factor n.

🔐 Play with toy RSA

👩 Alice (key owner)
p–
q–
φ–
d (private)–
🌍 Public (everyone sees)
n–
e–
ciphertext–
🕵️ Eve (attacker)

Eve only knows n, e and the ciphertext.

Each character is encrypted separately here so the math stays visible. Real RSA uses padding (OAEP) and a 2048-bit or larger n.

# toy_rsa.py: needs Python 3.8+ for pow(e, -1, phi)
p, q = 61, 53                  # secret primes
n = p * q                      # 3233, public modulus
phi = (p - 1) * (q - 1)        # 3120, secret
e = 17                         # public exponent
d = pow(e, -1, phi)            # 2753, private key

m = 65                         # message ('A')
c = pow(m, e, n)               # encrypt:  2790
assert pow(c, d, n) == m       # decrypt works

# --- Eve's attack: factor n by trial division ---
def factor(n):
    f = 2
    while f * f <= n:
        if n % f == 0:
            return f, n // f
        f += 1

p2, q2 = factor(n)             # (53, 61), instant for a tiny n
d2 = pow(e, -1, (p2 - 1) * (q2 - 1))
print(pow(c, d2, n))           # 65, Eve reads the message
# For a 2048-bit n this loop would need ~2^1024 iterations.
⚠️ The real-world record: the largest RSA challenge number factored publicly is RSA-250 (829 bits). It took about 2,700 CPU core-years in 2020 using the General Number Field Sieve. Each step up in key size makes the work grow sharply, so 2048-bit keys are far out of reach of known classical algorithms.

8. How This Holds Up the Internet

When you open https:// anything, your browser and the server run a TLS 1.3 handshake. Each step relies on a problem that is easy to verify and believed hard to solve. Step through it:

🤝 TLS 1.3 handshake: what each step relies on

  1. ClientHello: the browser sends random bytes and an X25519 (or hybrid X25519MLKEM768) key share a·G. Relies on: elliptic-curve discrete log. Eve can't get a from a·G.
  2. ServerHello: the server replies with its own key share b·G. Both sides now compute the shared secret ab·G. Relies on: the Diffie–Hellman problem. Seeing a·G and b·G doesn't reveal ab·G.
  3. Certificate: the server sends its certificate, signed by a Certificate Authority (CA). Relies on: RSA or ECDSA signatures. Forging a CA signature is an NP search problem.
  4. CertificateVerify: the server signs the handshake transcript with its private key, proving it owns the certificate. Relies on: the attacker can't derive the private key from the public key.
  5. Key derivation: both sides run HKDF-SHA256 over the shared secret to get session keys. Relies on: SHA-256 being hard to invert or collide.
  6. Application data: traffic is encrypted with AES-GCM or ChaCha20-Poly1305. Relies on: recovering the key from ciphertext being infeasible. Checking a guessed key is fast, so this is also an NP search problem.

The same building blocks show up almost everywhere:

🏦
Online banking

TLS plus signed transaction tokens

💬
WhatsApp / Signal

End-to-end encryption with X25519 key agreement

🖥️
SSH into servers

Ed25519 / RSA host and user keys

📦
Software updates

Signed packages (apt, App Store, Windows Update)

🔑
Passwords

Stored as bcrypt / Argon2 hashes, never plain text

🌐
DNSSEC

Signed DNS records so nobody can redirect your domain

₿
Cryptocurrency

ECDSA wallets + SHA-256 proof-of-work

🔀
Git commits

Hash-linked history, optional GPG/SSH signing

9. Bitcoin's Proof-of-Work: An NP Puzzle Running Worldwide

Bitcoin mining is a hash puzzle: find a number (a nonce) so that SHA-256(block + nonce) starts with enough zeros. The only known method is to keep guessing, but anyone can verify a winning nonce with one hash. This demo runs real SHA-256 in your browser.

⛏️ Mini miner

Press Mine to start guessing nonces.
💡 Each extra hex zero = 16× more guesses. Bitcoin's real difficulty needs roughly 19 leading hex zeros, and the whole network computes several hundred quintillion hashes per second. If P = NP, finding a valid nonce could become as easy as checking one, and Bitcoin's security model would stop working.

10. What If P = NP?

Suppose someone publishes a practical polynomial-time algorithm for SAT. Through reductions, every NP search problem becomes efficiently solvable, including "find the key that decrypts this" and "find a signature that verifies." Flip the switch to see what changes:

🌍 Our world: P ≠ NP (we assume)
HTTPS / TLS

Banking

Bitcoin & crypto

Software updates

Password databases

SSH / VPNs

Logistics

Medicine

Mathematics

P = NP would not affect everything. A one-time pad stays secure, because its security comes from information theory and not from a hard problem. Everything else in today's toolkit, including symmetric ciphers like AES, could in principle fall, because "find the key that turns this plaintext into this ciphertext" is an NP problem.

11. The Fine Print

"P = NP breaks the internet" is a good headline, but the real situation has some caveats:

"Polynomial" doesn't always mean "fast"

An algorithm running in n¹⁰⁰ steps is polynomial, but useless in practice. A proof of P = NP might come with an algorithm so slow that crypto stays safe in practice. The internet breaks only if the algorithm is practical.

The proof might not include an algorithm at all

A non-constructive proof could show that a fast algorithm exists without telling anyone what it is. That would be a mathematical earthquake but not an immediate security crisis.

P ≠ NP doesn't automatically make crypto safe

P ≠ NP is about worst-case hardness: some instances are hard. Crypto needs average-case hardness, meaning randomly generated keys must be hard to break. That is a stronger assumption, and it is also unproven. Cryptography is safe only if P ≠ NP, but P ≠ NP alone is not enough.

Factoring probably isn't NP-complete

Factoring is in NP, but it is not believed to be NP-complete. It is also in co-NP, and its best classical algorithm, the Number Field Sieve, is sub-exponential. Someone could find a fast factoring algorithm tomorrow without resolving P vs NP. RSA could fall while P ≠ NP still holds.

Quantum computers are a separate threat

Shor's algorithm (1994) factors numbers and solves discrete logs in polynomial time on a large quantum computer. That breaks RSA and elliptic-curve crypto without P = NP. Quantum computers are not believed to solve NP-complete problems efficiently. That's why the industry is migrating to post-quantum cryptography such as ML-KEM (Kyber) and ML-DSA (Dilithium), standardized by NIST in 2024 and already used in Chrome and Cloudflare's TLS. Those schemes still depend on P ≠ NP.

ScenarioRSA / ECCPost-quantum (lattices)AES / SHA-256
Today (assume P ≠ NP, no big quantum computer)✅ Safe✅ Safe✅ Safe
Large quantum computer built❌ Broken (Shor)✅ Believed safe⚠️ Weakened (Grover), so use 256-bit keys
Fast factoring found, P ≠ NP still holds❌ RSA broken✅ Safe✅ Safe
Practical P = NP algorithm found❌ Broken❌ Broken❌ Broken

12. Quiz: Classify the Problem

For each problem, pick the best description. Click an answer to see the explanation.

🧠 One-sentence summary: P means easy to solve, NP means easy to check, and internet security assumes there are problems that are easy to check but hard to solve. Proving P = NP with a practical algorithm would remove that assumption, and with it the basis of almost all modern encryption.
Copied to clipboard!