project-euler/0010-2.py
2018-03-28 13:07:45 +02:00

40 lines
1011 B
Python

# https://www.geeksforgeeks.org/sieve-sundaram-print-primes-smaller-n/
from functools import reduce
def sieve_of_sundaram(n):
# In general Sieve of Sundaram, produces primes smaller
# than (2*x + 2) for a number given number x.
# Since we want primes smaller than n, we reduce n to half
n_new = int((n-2) / 2);
# This array is used to separate numbers of the form i+j+2ij
# from others where 1 <= i <= j
marked = [ False ] * (n_new + 1)
# Main logic of Sundaram. Mark all numbers of the
# form i + j + 2ij as true where 1 <= i <= j
for i in range(1, n_new + 1):
j = i
while (i + j + 2 * i * j < n_new):
marked[i + j + 2*i*j] = True
j += 1
primes = []
if (n > 2):
primes.append(2)
for i in range(1, n_new):
if (marked[i] == False):
primes.append(2 * i + 1)
return primes
primes = sieve_of_sundaram(2000000)
print(reduce(lambda x, y: x + y, primes))
# answer 142913828922