Back

Two ways to find all prime numbers in a range

Sript description

This script has two ways of finding all the prime numbers within a range.The first way is to simply check every number and see if it is a prime number. The second way, which is a lot faster is to check every number, but also eliminate every multiple of it.

Result

Example

Source Code

import time
myRange = 10000


# one way
startTime1 = time.time()
for i in range(1, myRange):
    count = 0
    for o in range (1, i+1):
        if i % o == 0 and i != o and o != 1:
            count += 1
        if i % o == 0 and i==o and count == 0:
            print(i)

time1 = time.time()-startTime1
print(time1)





#2nd way
startTime2 = time.time()

isPrime = []
for i in range(0,myRange):
    isPrime.append(True)

for i in range (1, myRange):
    if isPrime[i] == True and i != 1:
        for o in range (2, int(myRange/i)):
            isPrime[i*o] = False

for i in range(0, len(isPrime)):
    if isPrime[i] == True:
        print(i)

time2 = time.time()- startTime2
print(time2)
print("range = ", myRange)
print("with 1st method: ", time1, "s and with 2nd method: ", time2,"s")