计算素数对数的程序

3 投票
4 回答
588 浏览
提问于 2025-04-17 06:16

数学规则显示,我的“程序”给出了错误的答案。

如果你能帮我检查这段小代码,并告诉我问题出在哪里,我将非常感激。我知道问题出现在 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`

4 个回答

0

文档里写着:

>>> from math import log
>>> log?
Type:       builtin_function_or_method
Base Class: <type 'builtin_function_or_method'>
String Form:<built-in function log>
Namespace:  Interactive
Docstring:
log(x[, base])

Return the logarithm of x to the given base.
If the base not specified, returns the natural logarithm (base e) of x.
1

这个是错的:

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)

应该是:

for i in range(501): ## from 0 to 500
  ll.append( log(lp[i],) )
6

你的第二个列表不仅仅包含质数的对数,它还包含了2到lp[500]之间所有整数的对数。

撰写回答