计算素数对数的程序

2024-04-25 08:21:38 发布

您现在位置:Python中文网/ 问答频道 /正文

数学规则表明我的“程序”给出了一个错误的答案。在

如果您能检查一下这段代码并告诉我它的问题,我将非常感激。我知道问题出在ll = []行之后。我只是不知道确切的原因。但我知道所有小于n的素数的对数之和小于n。我的程序违反了这个规则。在

代码如下:

from math import log
lp = [] ## create a list
for n in range(2,10000):
    for x in range(2,n):
        if n % x == 0:
            break
    else:
        lp.append(n) ## fill that list with the primes
##print lp[500] found the value of lp[500]
ll = [] ## create a second list
for i in range(2, lp[500]):
        if i < 3581: ## this is the number corresponding to lp[500]
            i = log(i, )
            ll.append(i) ## fill the second list with logs of primes
print sum (ll), 3581, sum(ll)/3581`

Tags: the代码in程序logforif规则
3条回答

这是错误的:

for i in range(2, lp[500]): ## Gives all numbers from 2 to lp[500]
    if i < 3581:
        i = log(i, ) ## this changes i which is your loop variable!
        ll.append(i)

应该是:

^{pr2}$

你的范围表达式

for i in range(2, lp[500]):

展开为从2到lp(独占)的第500个元素的所有数字。在

使用

^{pr2}$

会产生正确的结果。在

您的第二个列表不仅包含素数的日志,它还包含2到lp[500]之间的所有整数的日志。在

相关问题 更多 >