We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
defsieve_of_eratosthenes(max_n):"""Returns a list of prime numbers up to max_n."""is_prime=[True]*(max_n+1)p=2while(p*p<=max_n):if(is_prime[p]):foriinrange(p*p,max_n+1,p):is_prime[i]=Falsep+=1return[pforpinrange(2,max_n+1)ifis_prime[p]]defnth_prime(n,primes):"""Returns the nth prime number from the list of primes."""returnprimes[n-1]#nis1-indexed# Input processingT=int(input())test_cases=[int(input())for_inrange(T)]# Determine the maximum N to compute enough primesmax_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.importmathifmax_n<6:upper_bound=15#SmalladjustmentforsmallNvalueselse:upper_bound=int(max_n*(math.log(max_n)+math.log(math.log(max_n))))# Generate primes using the Sieve of Eratosthenesprimes=sieve_of_eratosthenes(upper_bound)# Output results for each test caseforNintest_cases:print(nth_prime(N,primes))
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Project Euler #7: 10001st prime
You are viewing a single comment's thread. Return to all comments →