``` #生成質數npy檔 v0.5 #Python #更新時間: 2022.11.2 #Generate prime number strings #生成所有不大於t 的質數,用來質因數分解 t^2 內的數。for t > 10^12 ''' prime10^10 1 1.1.txt 檔案大小是 495mb prime10^10 8.2 8.3.txt 檔案大小是 455mb prime10^11 7.11 7.12.txt 檔案大小是 454mb If t <= 10^8: use eratosthenes(t). else: use gmpy2.is_prime(t). 質數列表 https://bit.ly/3TsOtce 質數計算函數 https://bit.ly/3gxCbkh https://en.wikipedia.org/wiki/Probable_primed 速度 i%3 and i%5 and i%7 and gmpy2.is_prime(i) > i%3 and i%5 and gmpy2.is_prime(i) > gmpy2.is_prime(i) > i%3 and i%5 and i%7 and i%11 and gmpy2.is_prime(i) ''' import gmpy2, time, pygame pygame.mixer.init() soundObj = pygame.mixer.Sound('Se11.wav') #方法1.6: 使用np.save存檔 for t >= 10^12 def P(u1,s1): t = 10**u1 #u1 = 11 #s1 = 8.76 #起始值 u2 = u1-9 b1 = 10**u2 b2, b3 = b1*10, 1/b1 s2 = t//b1 # 10**(u1-2) s3 = round(s1*b1) t1 = s2*s3+1 for i1 in range(s3,b2): start = time.process_time() x1 = np.array([i for i in range(t1,t1+s2,2) if i%3 and i%5 and i%7 and gmpy2.is_prime(i)]) s1 += b3 t1 += s2 end = time.process_time() fn2 = f'10^{u1} {s1-b3:.{u2}f} {s1:.{u2}f}' j2 = len(x1) print(f'{fn2} 費時{end-start:.2f}秒, {j2}個質數', time.ctime()) fn3 = f'p{fn2}.npy' np.save(fn3, x1) soundObj.play() #當i1+=1時,播放聲音,提醒自己進入下一階段 #- - #方法1.5: 使用gmpy2.is_prime找出質數 for t >= 10^11 def P(u1,s1): #gc.collect() t = 10**u1 #u1 = 11 #s1 = 8.76 #起始值 b1 = 10**(u1-9) b2, b3 = b1*10, 1/b1 s2 = t//b1 # 10**(u1-2) s3 = round(s1*b1) t1 = s2*s3+1 for i1 in range(s3,b2): start = time.process_time() x1 = [i for i in range(t1,t1+s2,2) if i%3 and i%5 and i%7 and gmpy2.is_prime(i)] s1 += b3 t1 += s2 end = time.process_time() fn2 = f'10^{u1} {s1-b3:.2f} {s1:.2f}' fn1 = f'prime{fn2}.txt' j2 = len(x1) print(f'{fn2} 費時{end-start:.2f}秒, {j2}個質數', time.ctime()) xs = sd(x1) #刪除 str(x1) 內的 '[', ']', ',' 檔案大小可減少10% with open(fn1, 'w') as fn: fn.write(xs) #儲存字串xs #del i #刪除變數 #gc.collect() #回收機制 soundObj.play() #當i1+=1時,播放聲音,提醒自己進入下一階段 if __name__ == '__main__': P(11,8.63) #- - def sd(x1): #input 為 質數list xs = str(x1) #刪除 str(x1) 內的 '[', ']', ',' 檔案大小可減少10% xs = xs.replace("[", "") xs = xs.replace("]", "") xs = xs.replace(",", "") return xs #方法1.4: 使用gmpy2.is_prime找出質數 for t > 10^11 if __name__ == '__main__': #gc.collect() u1 = 11 t = 10**u1 s1 = 1 #起始值 (出現 MemoryError) s2 = t//100 # 10**(u1-2) s3 = round(s1*100)-100 t1 = t+s2*s3 + 1 t2 = t1+s2-2 for i1 in range(s3,1000): x1 = [] j2 = 0 start = time.process_time() for i in range(t1,t2,2): if i % 3 and gmpy2.is_prime(i): x1.append(i) j2 += 1 #計算質數的數量 s1 += 0.01 t1 += s2 t2 += s2 end = time.process_time() fn2 = f'10^{u1} {s1-0.01:.2f} {s1:.2f}' fn1 = f'prime{fn2}.txt' print(f'{fn2} 費時{end-start:.2f}秒, {j2}個質數',time.ctime()) xs = sd(x1) #刪除 str(x1) 內的 '[', ']', ',' 檔案大小可減少10% with open(fn1, 'w') as fn: fn.write(xs) #儲存字串xs #del i #刪除變數 #gc.collect() #回收機制 soundObj.play() #當i1+=1時,播放聲音,提醒自己進入下一階段 ```