From 6379f01abc9ac35c128cb940bfe6dae046e73ea3 Mon Sep 17 00:00:00 2001 From: Linus Miller Date: Wed, 28 Mar 2018 13:07:45 +0200 Subject: [PATCH] Alternative solutions to problem 10 --- 0010-1.py | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ 0010-2.py | 39 +++++++++++++++++++++++++++++++++++++++ 0010.py | 2 ++ 3 files changed, 91 insertions(+) create mode 100644 0010-1.py create mode 100644 0010-2.py diff --git a/0010-1.py b/0010-1.py new file mode 100644 index 0000000..7897346 --- /dev/null +++ b/0010-1.py @@ -0,0 +1,50 @@ +from functools import reduce +# from collections import deque + +n = 2000000 +# n = 100 + +array = list(range(3, n)) + +# array[0] = None +# array[1] = None + +primes = [] + +p = 2 + +def next(): + # num = array.popleft() + + # while (num == None and len(array) > 0): + # num = array.popleft() + + # return num + global array + + for idx, num in enumerate(array): + idx + if (num != None): + array = array[idx + 1:] + + print(num) + print(idx) + return num + +while (p != None): + print(p) + primes.append(p) + + count = 1 + i = count * p - 1 + length = len(array) + print(length) + + for i in range(p - 1, length, p): + array[i] = None + + p = next() + + +print(primes) + diff --git a/0010-2.py b/0010-2.py new file mode 100644 index 0000000..c8ee826 --- /dev/null +++ b/0010-2.py @@ -0,0 +1,39 @@ +# 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 diff --git a/0010.py b/0010.py index 2006d26..8b329aa 100644 --- a/0010.py +++ b/0010.py @@ -12,3 +12,5 @@ for i in range(2, 2000000): result = reduce(lambda x, y: x + y, primes) print(primes) print(result) + +# answer 142913828922