은 주어진 알고리즘 중 하나가 소수를 생성하는 것입니다 :왜이 알고리즘이 더 나 빠릅니까? <a href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes" rel="nofollow">Wikipedia</a>이에서
def eratosthenes_sieve(n):
# Create a candidate list within which non-primes will be
# marked as None; only candidates below sqrt(n) need be checked.
candidates = [i for i in range(n + 1)]
fin = int(n ** 0.5)
# Loop over the candidates, marking out each multiple.
for i in range(2, fin + 1):
if not candidates[i]:
continue
candidates[i + i::i] = [None] * (n // i - 1)
# Filter out non-primes and return the list.
return [i for i in candidates[2:] if i]
내가 약간 알고리즘을 변경했습니다.
def eratosthenes_sieve(n):
# Create a candidate list within which non-primes will be
# marked as None; only candidates below sqrt(n) need be checked.
candidates = [i for i in range(n + 1)]
fin = int(n ** 0.5)
# Loop over the candidates, marking out each multiple.
candidates[4::2] = [None] * (n // 2 - 1)
for i in range(3, fin + 1, 2):
if not candidates[i]:
continue
candidates[i + i::i] = [None] * (n // i - 1)
# Filter out non-primes and return the list.
return [i for i in candidates[2:] if i]
나는 처음 2의 모든 배수를 표시하고 나는 단지 홀수 고려했다. 내가 두 알고리즘 (40.000.000 시도)을 타임 아웃했을 때 첫 번째 알고리즘은 항상 더 좋았습니다. 나는 왜 그런지 이해하지 못한다. 누군가 제발 설명해 줄 수 있니?
추신 : 100.000.000을 시도하면 컴퓨터가 정지합니다. 왜 그런가요? 나는 Core Duo E8500, 4GB RAM, Windows 7 Pro 64 Bit를 가지고있다.
업데이트 1 : 이것은 파이썬 3
이다가 업데이트 2 : 이것은 내가 시간이 초과하는 방법입니다
start = time.time()
a = eratosthenes_sieve(40000000)
end = time.time()
print(end - start)
가 UPDATE
: (특히 nightcracker 윈스턴 Ewert로) 소중한 의견되면 내가가 관리 내가 처음에 의도 코드 :def eratosthenes_sieve(n):
# Create a candidate list within which non-primes will be
# marked as None; only c below sqrt(n) need be checked.
c = [i for i in range(3, n + 1, 2)]
fin = int(n ** 0.5) // 2
# Loop over the c, marking out each multiple.
for i in range(fin):
if not c[i]:
continue
c[c[i] + i::c[i]] = [None] * ((n // c[i]) - (n // (2 * c[i])) - 1)
# Filter out non-primes and return the list.
return [2] + [i for i in c if i]
이 알고리즘에 의해 (맨 위에 언급 한) 원래 알고리즘을 개선 (보통 ly) 50 %. (그래도 나이트 크래커가 언급 한 알고리즘보다 나쁘다.)
파이썬 마스터에게 질문 : 마지막 코드를 좀 더 기능적인 방식으로 표현하는 Python 방식이 있습니까?
업데이트 2 : 나이트 크래커가 언급 한 알고리즘을 디코딩 할 수 없었습니다. 나는 너무 바보 같아.
이 '기능 프로그래밍'은 어디에 있습니까? – Javier
아마도 for 루프를 사용하여'range' 대신'xrange'를 사용하여 비트를 더 빠르게 만들 수 있습니다. – GWW
나는 정반대를 찾고 있습니다. 어떻게 타이밍을하고 있습니까? –