數學規則顯示我的「程序」給出了錯誤的答案。計算素數的日誌
如果你能檢查這一小段代碼並告訴我它的問題,我將不勝感激。我知道問題在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`
需要多長時間計算質量達10000?在一個半線變化時,我可以在0.11s內計算它們。只要將範圍(2,n)中的x改爲':在lp中將x改爲':'。如果你想再快一點,就停在n的平方根處。在實施它們之前,嘗試理解這兩個小改動。所以相同的算法,只是一點點優化:https://gist.github.com/1347515(第三次更改,步驟設置爲2,沒有增加太多)。 – rplnt