0

我的素数函数对于大于 3 的数字运行良好,我已经在随后的循环中解释了这一点,问题是找到第 10001 个素数,但我得到错误的答案是素数但不是第 10001 个,应该是 104743

def pr(n):
    for i in range(2,int(n**(0.5))+1):
        if n%i==0:

        return False
        break   
    else:
        return True
num = 3
count = 2       
while count < 10001:
    num += 1
    x = pr(num)
    if x == True:
        count += 1

print num
4

2 回答 2

0
def pgen(): # Sieve of Eratosthenes generator
    yield 2
    np_f, q = {}, 3
    while True:
        f = np_f.pop(q, None)
        if f:
            np = q + f
            while np in np_f:
                np += f
            np_f[np] = f
        else:
            yield q
            np_f[q*q] = q+q
        q += 2

>>> p = pgen()
>>> [next(p) for i in xrange(10001)][-1]
104743
于 2013-10-20T21:47:04.610 回答
0

尝试;

def pr(n):
    if n%2 == 0:
        return False
    for i in range(3,int(n**(0.5))+1,2):
        if n%i==0:
            return False
    return True
于 2013-10-20T21:28:46.017 回答