Problem 50 Consecutive prime sum

2016-11-15 09:52:00   技术   python projecteulor

The prime 41, can be written as the sum of six consecutive primes:

\[41 = 2 + 3 + 5 + 7 + 11 + 13\]

This is the longest sum of consecutive primes that adds to a prime below one-hundred.

The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953.

Which prime, below one-million, can be written as the sum of the most consecutive primes? import math

PRIME_LIST = []
PRIME_RANGE = 545


def is_Prime(number):
    if number < 2:
        return False
    for x in range(2, int(math.sqrt(number)) + 1):
        if number % x == 0:
            return False
    return True

prime_count = 0
index = 1
while prime_count < PRIME_RANGE + 1:
    if is_Prime(index):
        PRIME_LIST.append(index)
        prime_count += 1
    index += 1


max_count = 0
final_result = 0
start = 0

while start < PRIME_RANGE and PRIME_RANGE - start > max_count:
    result = 0
    count = 0
    for prime in PRIME_LIST[start:]:
        if result + prime >= 1000000:
            break
        count += 1
        result += prime
        if is_Prime(result):
            if count > max_count:
                max_count = count
                final_result = result

    start += 1

print max_count, final_result

在处理循环跳出条件上转了几圈 PRIME_RANGE = 545 这是一个知道答案之后输入的magic number 关于素数的好几题我都在纠结,使用一个素数表可以加快效率,但是,究竟需要多大的素数表也是一个问题

评论已关闭。
评论共