提问人:Jman5213 提问时间:11/13/2023 更新时间:11/13/2023 访问量:96
十亿分之一素数算法和语言 [已关闭]
Billionth prime number algorithm and language [closed]
问:
我想在没有非常大的计算机的情况下快速计算至少十亿分之一的素数。我应该使用什么方法和编程语言来避免内存不足,并且仍然在合理的时间内完成程序?
我用这个脚本尝试过python:
from math import sqrt
from time import perf_counter
c=int(input("calculate the nth prime #: "))
n=1#currentNum
f=0#primesFound
l=1#latestPrime
x=perf_counter()
def p(f):
for i in range(3,int(sqrt(f)+1),2):
if f%i==0:
return False
return True
while f<c:
if p(n):
f+=1
l=n
n+=2
y=perf_counter()
print('Your num:',str(l)+'\nTime:',str(y-x)+"sec")
我也尝试过在 python 中使用 eratosthenes 的 seive,但以下代码遇到了内存错误:
import math
from time import perf_counter
def sieve_of_eratosthenes(limit):
sieve = [True] * (limit + 1)
sieve[0] = sieve[1] = False
for p in range(2, int(limit ** 0.5) + 1):
if sieve[p]:
for i in range(p * p, limit + 1, p):
sieve[i] = False
primes = [p for p, is_prime in enumerate(sieve) if is_prime]
return primes
c = int(input("Calculate the nth prime num: "))
x = perf_counter()
"""Calculate the estimated upper limit based on the nth prime"""
estimated_limit = int(c * (math.log(c) + math.log(math.log(c))))
primes = sieve_of_eratosthenes(estimated_limit)
y = perf_counter()
if c <= len(primes):
nth_prime = primes[c - 1]
print('Your num:', nth_prime, '\nTime:', y - x, "sec")
else:
print('There are not enough prime numbers in the precomputed list.')
答: 暂无答案
评论