- Consecutive prime sum
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?https://projecteuler.net/problem=50
- 解答例 (Ruby)
require 'prime' k = 1_000_000 sum = 0 prime = Prime.each(k).to_a i = 0 loop do if sum + prime[i] < k sum += prime[i] else break end i += 1 end if Prime.prime?(sum) p sum else i = 0 loop do sum -= prime[i] if Prime.prime?(sum) p sum break else i += 1 end end end