3
Python计算素数学习记录
source link: https://blog.51cto.com/u_15477789/5429950
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Python计算素数学习记录
原创计算一定范围内的素数,并记录在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}')
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计算用时:
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK