I am making a Sieve of Eratosthenes implementation in Python. A problem that occurs is not all primes appear (mainly the lower numbered ones).
Here is my code:
def prevPrimes(n):
from math import sqrt
from time import time
start = time()
if type(n) != int and type(n) != long:
raise TypeError("Arg (n) must be of <type 'int'> or <type 'long'>")
if n <= 2:
raise ValueError("Arg (n) must be at least 2")
limit, x, num, primes = sqrt(n), 2, {}, []
for i in range(1, n+1):
num[i] = True
while x < limit:
for i in num:
if i%x==0:
num[i] = False
x += 1
for i in num:
if num[i]:
primes.append(i)
end = time()
primes = sorted(primes)
print round((end - start), 2), ' seconds'
return primes
If I input >>> prevPrimes(1000)
, I would expect the result to start out as: [2, 3, 5, 7, 11, 13, 17]
etc. However, this is what it looks like: [1, 37, 41, 43, 47, #more numbers]
.
I know that the issue lies in the fact that it is stating the 'original' primes (2, 3, 5, 7, 11, 13, 17, etc.) as False
because of the way my program checks for the primes. How can I avoid this? Thanks in advance :)