Very FAST Prime Number Finder Code (python)

I noticed that my previous code was slow, since the print command is VERY slow.
It slows python down quite a bit, so I made it print less frequently.
It does the same thing, though.

from timeit import default_timer as timer
import timeit
print("Starting Calculation...")
start = timer()
primeList = [2]
text_file = open("Primes.txt", "w")
text_other_file = open("PrimesLists.txt", "w")
max = 100000000 # checks the integers between two and max
interval = 50000 # gives timer notification at every interval in seconds

prevStart = 0 

for x in range(3, max + 1, 2):
    isPrime = True
    if (x % interval) - 1 == 0:
        time = timer() - start
        print("{:,d}".format(x - 1) + " : " + str("{0:.2f}".format(time)) + " seconds elapsed, or " + str("{0:.2f}".format(time / 60)) + " minutes elapsed, " + str("{0:.2f}".format(timer() - prevStart)) + " second gap")
        prevStart = timer()
    for y in primeList:
        if y > (x**0.5):
            break
        if x % y == 0:
            isPrime = False
            break
    if isPrime:
        primeList.append(x)

end = timer()
print("Done Calculating All The Primes From 2 Through " + str(max))
print("Completed in " + str(end - start) + " seconds")

for z in range(0, len(primeList) - 1):
    text_file.write(str(primeList[z]) + "\n")
    text_other_file.write(str(z + 1) + ". " + str(primeList[z]) + "\n")
print("Successfully written to text file")
print("Completed in " + str(timer() - end) + " seconds")
text_file.close()
text_other_file.close()

Hope you like it!
Here’s the prime numbers between 2 and 100,000,000.
PrimesFromTwoThrough100MillionCornerspots
Note: If notepad will open the file, it just takes around 10 seconds to open. It will say not responding, but just wait and it will open.

 

 

Leave a Comment