이것은 프로젝트의 오일러에서 10 번째 문제입니다.이 문제는 2 백만 이하의 소수를 모두 합한 것입니다. 나는 Saw 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.
먼저 소수로 배열을 채우고 합계를 계산하십시오. 시도하고 말해봐? – bhansa
나는이 질문을 다시 읽고 그것에 대한 의견을 나누기 바란다. –
내부 루프에서'if not (i % 10) : print (i, "", sum_of_prime)와 같은 방법으로 인쇄하는 양을 줄일 수 있습니다. – martineau