n = int(input("input n"))
prime = [2]
base = 3
order = 0
while base < n + 1:
if order < len(prime):
if base % prime[order] == 0:
order = len(prime)
else:
order += 1
else:
prime.append(base)
order = 0
base += 1
print (prime)
I am trying to create a list of prime numbers from 1 to given number 'n'. (ignoring the case for numbers less than 3)
What I intend to do is:
- bring first number from 3 to n (let's call this base)
- compare base to first number in prime list (in this case, 2)
- if the base is not divisible, compare this to next number in prime list.
- repeat step 3 until all numbers in the prime list are compared or at least one number divisible to base in the prime list appears.
- if base compared to all numbers in the prime list and is not divisible by any of them, append base to prime list.
- increase the value of base by 1 and repeat step 2 to 5 upto base = n.
Whatever the value i put for n, i only get single value of 2 in the prime list printed. Please help to find out which part is wrong.