2011-11-14 55 views
3

數學規則顯示我的「程序」給出了錯誤的答案。計算素數的日誌

如果你能檢查這一小段代碼並告訴我它的問題,我將不勝感激。我知道問題在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` 
+0

需要多長時間計算質量達10000?在一個半線變化時,我可以在0.11s內計算它們。只要將範圍(2,n)中的x改爲':在lp中將x改爲':'。如果你想再快一點,就停在n的平方根處。在實施它們之前,嘗試理解這兩個小改動。所以相同的算法,只是一點點優化:https://gist.github.com/1347515(第三次更改,步驟設置爲2,沒有增加太多)。 – rplnt

回答

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. 
6

第二個清單並不只包含素數的日誌,它包含了2 lp[500]之間的所有整數的日誌。

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],)) 
1

你的範圍表達

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

擴展到所有數字爲2至的lp第500元素(不包括) 。

使用

for i in lp: 

應產生正確的結果。