Problem description:
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10001st prime number?
Prime number:
A prime number is a whole number greater than 1 whose only factors are 1 and itself. A factor is a whole number that can be divided evenly into another number.
Example:
The first 25 prime numbers (all the prime numbers less than 100) are:
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97
The best solution is with Sieve Of Eratosthenes
Sieve Of Eratosthenes:
In mathematics, the sieve of Eratosthenes is an ancient algorithm for finding all prime numbers up to any given limit.
It does so by iteratively marking as composite (i.e., not prime) the multiples of each prime, starting with the first prime number, 2.
The multiples of a given prime are generated as a sequence of numbers starting from that prime, with constant difference between them that is equal to that prime.
This is the sieve's key distinction from using trial division to sequentially test each candidate number for divisibility by each prime.
Once all the multiples of each discovered prime have been marked as composites, the remaining unmarked numbers are primes.
The sieve of Eratosthenes is one of the most efficient ways to find all primes smaller than n when n is smaller than 10 million or so.
Sieve Of Eratosthenes(Step by Step):
1- Create a list of consecutive integers from 2 through n: (2, 3, 4, ..., n).
2- Initially, let p equal 2, the smallest prime number.
3- Enumerate the multiples of p by counting in increments of p from 2p to n, and mark them in the list (these will be 2p, 3p, 4p, ...; the p itself should not be marked).
4- Find the smallest number in the list greater than p that is not marked. If there was no such number, stop. Otherwise, let p now equal this new number (which is the next prime), and repeat from step 3.
5- When the algorithm terminates, the numbers remaining not marked in the list are all the primes below n.
My Solution
This is my solution for problem 7 of Project Euler using Python:
def sieve_of_eratosthenes(n):
'''method for finding all primes up to
a given natural n.
'''
is_prime = [True]*n
is_prime[0] = False
is_prime[1] = False
for i in range(2,int(math.sqrt(n)+1)):
index = i*2
while index < n:
is_prime[index] = False
index = index+i
prime = []
for i in range(n):
if is_prime[i] == True:
prime.append(i)
return prime
How could my code be improved?
n
? It is not 10,001. There are gaps in the list of primes -- you need to terminate whenlength(prime)
reaches 10,001, not whenn
does. \$\endgroup\$