Question

I am new to python and I am trying to make a prime numbers generator in a range, I found this code online:

from math import sqrt
import time
t1 = time.time()
primenumbers=[2,3,5]

for i in range(7,1000,2):
    sq = sqrt(i)+1
    for j in primenumbers:
        if sq < j:
            primenumbers.append(i)
            #print i, len(primenumbers)
            break

        if i % j == 0:
            break

print primenumbers
t2 = time.time()
print (t2 - t1)

but if I change

for i in range(7,1000,2):

with

for i in range(10,1000,2):

in output I only get numbers 2 3 and 5, and if I make the primenumbers array empty instead of it containing 2 3 and 5, in output I get an empty array, it won't be filled with prime numbers. If you can just tell me what is wrong, I can't figure it out

Was it helpful?

Solution

You need to understand the range function to get this behavior (and the essence of the program you used too).

range(7,1000,2) gives you a list of integers starting from 7 which are less than 1000 and are computed by adding 2 to previous number - so the series of numbers that you get are 9,11,13,15.. and so on.

range(10,1000,2) gives you a list of integers starting from 10 and which all will be divisible by 2 hence no primes in the list.

-- This program can help you --

primes = []
for i in range(1,100,2): # <==== change here - make sure first argument is odd
  prime = True
  for j in range(2,i-1):
    if i % j == 0:
      prime = False
      break
  if prime:
    primes.append(i)
print primes
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top