Project Euler Problem 7

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.

Project Euler Problem 7

Solution

To find the $10{,}001^\text{st}$ prime, we generate prime numbers sequentially and count them until reaching the target index.

A standard approach is:

  • Start from $2$
  • Test each candidate for primality using trial division up to $\sqrt{n}$
  • Count primes found
  • Stop when the count reaches $10{,}001$

Here is clean Python code:

def is_prime(n):
    if n < 2:
        return False
    if n == 2:
        return True
    if n % 2 == 0:
        return False

    d = 3
    while d * d <= n:
        if n % d == 0:
            return False
        d += 2

    return True

count = 0
num = 1

while count < 10001:
    num += 1
    if is_prime(num):
        count += 1

print(num)

Tracing the logic:

  • The primes begin:

$2,3,5,7,11,13,\dots$

  • The counter increases only when a prime is found.
  • Continuing this process until the $10{,}001^\text{st}$ prime gives:

Answer: 104743