2017-01-17 10 views
1

これは、プロジェクト・オイラーの10番目の問題です。この問題では、200万未満の素数の合計を求めることになっています。私は素数を見つけるためにSag of Eratosthenesアルゴリズムを使用しています。今、私は直面しており、Sieve of Eratosthenesアルゴリズムのパフォーマンスに問題があります。エラトステネス篩アルゴリズムの実装の問題

print(i,"",sum_of_prime)がループ内にあると、パフォーマンスが大幅に低下します。それが動作し、パフォーマンスを維持するためにとにかくありますか?これが従来の方法で行われた場合は、結果を得るまでに約13分かかります。

#Euler 10 

#Problem: 
#The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. 
#Find the sum of all the primes below two million. 

#Author: Kshithij Iyer 
#Date of creation: 15/1/2017 

import time 
#Recording start time of the program 
start=time.time() 
def sum_of_prime_numbers(limit): 
    "A function to get the sum prime numbers till the limit" 
    #Variable to store the sum of prime numbers 
    sum_of_prime=0 
    #Sieve of Eratosthenes algorithm 
    sieve=[True]*limit 
    for i in range(2,limit): 
     if sieve[i]: 
      sum_of_prime=sum_of_prime+i 
      for j in range(i*i,limit,i): 
       sieve[j]=False 
      print(i,"",sum_of_prime) 
    print("The sum of all the prime numbers below",limit,"is",sum_of_prime) 
    return 
#sum_of_prime_numbers(10) 
sum_of_prime_numbers(2000001) 
print("Execution time of program is",time.time()-start) 

#Note: 
#I did give the conventioanl method a try but it didn't work well and was taking 
#some 13 minutes to get the results. 

#Algorithm for reference 
#Input: an integer n > 1 

#Let A be an array of Boolean values, indexed by integers 2 to n, 
#initially all set to true. 

#for i = 2, 3, 4, ..., not exceeding √n: 
#if A[i] is true: 
#for j = i2, i2+i, i2+2i, i2+3i, ..., not exceeding n : 
#A[j] := false 

#Output: all i such that A[i] is true. 
+0

最初に素数で配列を取り込み、合計を計算してください。試して教えて? – bhansa

+0

私はそれを読んで、あなたの意見を共有してください質問を改めました。 –

+0

内部ループの '' not(i%10):print(i、 ""、sum_of_prime)のようなもので印刷の量を減らすことができます。 – martineau

答えて

0
だからここに作ることができる様々な改良がある

まず、原因エラトステネスふるいの性質のためには、あなたはfor i in range(2,int(limit**0.5)+1):for i in range(2,limit):を置き換えることができ、アレイが正常に計算されますが、はるかに高速になります;しかし、その結果、後で数字を合計する必要があります。

また、すべてのプライムを読むことはできませんし、あなたもしたいと思いません。代わりに、プログラムが特定の番号に達するたびにマイルストーンを伝えるプログラムが必要です。

あなたのプログラムは、配列が0から始まるという事実を考慮していないようです。しかし、これはかなり修正可能でなければなりません。

最後に、あなたのプログラムはプライムとして1をカウントするように見えます。これはもう一つの簡単な修正であるはずです。

+0

2からのループ統計と1つも決して考慮されません。推測する前にアルゴリズムを参照してください。 –

+0

私が言っていることは、私が提案した(そしてはるかに速い)方法を使うためには、いくつかの編集をしなければならないということです。現在は出力には表示されませんが、後者の2つの問題が私の提案に当てはまります。 –

+0

ありがとうございます。 –