計算一定范圍內的素數,並記錄在json文件中。下次計算可以在上次的基礎上迭代
在從3開始計算素數的情況下,計算100萬內的素數能在1秒內完成
import json
import time
start = time. time()
limit = 1e6
try:
with open ( 'prime.json', 'r') as file:
list = json. load( file)
num = list[ - 1]
except FileNotFoundError:
list = [ 3]
num = 3
def check( num):
for i in list:
if num % i == 0:
break
elif i * i > num: #這裡千萬不要寫成i**2,計算速度會慢2倍多
list. append( num)
#print(num)
break
while num < limit:
num = num + 2
check( num)
# with open ('prime.json', 'w') as file:
# json.dump(list,file,indent=4)
print( list[ - 1])
end = time. time()
print( f'本次計算用時:{ end - start} ')
i5-10400計算用時:
Montage Jintide(R) C4215R(CentOS服務器,3.2GHz)計算用時:
i5-6200U計算用時: