1

I want to find all the prime numbers below 1 million in 1 second or as close to it as possible.
Here is my code:-

import time
n = 1000000
start = time.time()

primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 
61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 
149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 
229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 
313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 
409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 
499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 
601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 
691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 
809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 
907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]
for j in range(1,n+1):
    for i in range(0,len(primes)):
        if j % primes[i] == 0:
                break
    else:
        primes.append(j)
#print primes
end = time.time() - start
print end    

I know it is technically cheating but I just want to make it faster.
Current time = 2.5 seconds(approx)

Is it possible to compute all this in 1 second or close?

luciferchase
  • 559
  • 1
  • 10
  • 24

1 Answers1

3

You can use the Sieve of Eratosthenes, implemented below:

EDIT: Added modifications to speed it up a bit, thanks to @rossum.

n = 1000000

is_prime = [False, False] + [True] * (n - 1)
primes = [2]

for j in range(4, n + 1, 2):
    is_prime[j] = False

for i in range(3, n + 1, 2):
    if is_prime[i]:
        primes.append(i)
        for j in range(i * i, n + 1, i):
            is_prime[j] = False

print len(primes) # ==> 78498, which is really the number of primes below 1 million
print primes[:10] # ==> [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

It takes about 1 to 2 seconds on my computer.

DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
  • 1
    There are two speed ups I can see. First, treat 2 separately so then the outer loop only needs to examine odd numbers: 3, 5, 7, ... That will nearly halve the time taken. Second, your inner loop can start at `i * i` instead of `2 * i` which saves a little more time and still works since all possible prime factors below `i` have already been processed. – rossum Mar 17 '19 at 12:53