Trying to implement Wikipedia's pseudocode version of Sieve of Eratosthenes' prime number algorithm.
Pseudo code:
algorithm Sieve of Eratosthenes is
input: an integer > 1.
output: all prime numbers from 2 through .
let be an array of Boolean values, indexed by integers 2 to ,
initially all set to true.
for = 2, 3, 4, ..., not exceeding √ do
if [] is true
for = ², ²+, ²+2, ²+3, ..., not exceeding do
set [] := false
return all such that [] is true.
My code:
def createListOfPrimes():
n = int(input("Enter an integer n>1: "))
in_list = [True]*(n+1)
for i in range(2, int(math.sqrt(n)+1)):
if in_list[i] == True:
for j in range(i**2, n+1, i):
in_list[j] == False
print(i)
Can someone explain why the function prints wrong values, e.g. for n = 90 createListOfPrimes()
prints integers from 2 to 9 inclusively. Been scratching my head over why it's not working - tried various indenting structures with no luck.
EDIT: Implemented @trincot's advise, seems to work. Any suggestions on code improvement are welcomed!
def createListOfPrimes():
n = int(input("Enter an integer n>1: "))
in_list = [True]*(n+1)
prime_list = []
for i in range(2, int(math.sqrt(n)+1)):
if in_list[i] == True:
for j in range(i**2, n+1, i):
in_list[j] = False
for i in range(2,n+1):
if in_list[i]==True:
prime_list.append(i)
return prime_list