I have this program to list prime numbers within a certain range. the problem is the larger the number the slower it becomes. how can i use numpy to imporve the speeds? if not numpy, is there any other way to speed up the calculations?
from datetime import date
import time
import numpy as np
today = date.today()
lower = int(input("Starting Number: "))
upper = int(input("Ending Number: "))
print("Prime numbers between",lower,"and",upper,"are:")
with open("primenumbers.txt","a") as file:
file.write("\n")
file.write("{}".format(today))
file.write("\n")
start = time.time()
for num in range(lower,upper + 1):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)
with open("primenumbers.txt","a") as file:
file.write("\n")
file.write("{}".format(num))
end = time.time()
print(end - start)
i want to process the data faster and please show some code.
for i in range(2,num): if (num % i) == 0... Oh, my... Please first optimize the values you are trying to compare. If the number is prime, then it will be odd and should have a divisor such thatdivisor <= sqrt(num)Including even numbers doubles the number of iterations you are performing, and searching all the way up to the number makes the number of iterations absolutely massive compared to searching up-to the square-root. Please go read up on Number Theory. Ideally, you should be caching in a sieve and using that to optimize your search.