Project Euler #7: 10001st prime

  • + 0 comments
    def sieve_of_eratosthenes(max_n):
        """Returns a list of prime numbers up to max_n."""
        is_prime = [True] * (max_n + 1)
        p = 2
        while (p * p <= max_n):
            if (is_prime[p]):
                for i in range(p * p, max_n + 1, p):
                    is_prime[i] = False
            p += 1
        return [p for p in range(2, max_n + 1) if is_prime[p]]
    
    def nth_prime(n, primes):
        """Returns the nth prime number from the list of primes."""
        return primes[n - 1]  # n is 1-indexed
    
    # Input processing
    T = int(input())
    test_cases = [int(input()) for _ in range(T)]
    
    # Determine the maximum N to compute enough primes
    max_n = max(test_cases)
    
    # Estimate upper bound for the nth prime using the prime number theorem
    # n * log(n) is a rough estimate for the nth prime.
    import math
    if max_n < 6:
        upper_bound = 15  # Small adjustment for small N values
    else:
        upper_bound = int(max_n * (math.log(max_n) + math.log(math.log(max_n))))
    
    # Generate primes using the Sieve of Eratosthenes
    primes = sieve_of_eratosthenes(upper_bound)
    
    # Output results for each test case
    for N in test_cases:
        print(nth_prime(N, primes))