python用筛法输出指定范围素数个数
1 import time 2 stime = time.time() 3 def q(n): 4 is_prime = {x:True for x in range(n+1)} # 生成一个n个元素的字典 key设置为0-n+1 值设置为True 5 del is_prime[0] #删除0 6 for c in (2,3,5,7): 7 for z in range(2,int(n/2)): # 除以2因为c乘到一半就等于n了 再往下继续乘就大于n了 8 try: 9 index = c * z 10 if index > n: 11 pass 12 else: 13 print(index) 14 del is_prime[index] 15 except: 16 pass 17 print(len(is_prime)) 18 19 q(1000000) 20 etime = time.time() - stime 21 ftime = str(etime) 22 print('耗时:'+ftime)