I'm trying to find all primes below 1 000 000. As all non-primes can be factorised into primes, my method is to start my list of primes as [2, 3] and then run through every number up to 1 000 000. If a number is divisible by any number in prime_list, then it's not prime, and I move onto the next number. If this number isn't divisible by any number in prime_list, then it must be prime, and it gets added to this list.
To try and make this more efficient, I added a statement to only check if a number in question is divisible by values below the square root of this number. I thought this would cut out a lot of computation time but it actually makes my program take longer. Can anyone explain why?
Here's my code:
import math
import time
start_time = time.time()
prime = [2, 3]
def prime_checker(a):
for j in prime:
if j < (int(math.sqrt(a)) +1 ): /// without this line, the program runs faster
if a % j == 0:
return False
for i in range (2, 100000):
if prime_checker(i) != False:
prime.append(i)
print prime[-1]
print "Time taken = ", time.time() - start_time