Alternative solutions to problem 10
This commit is contained in:
parent
d3167ead99
commit
6379f01abc
50
0010-1.py
Normal file
50
0010-1.py
Normal file
@ -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)
|
||||||
|
|
||||||
39
0010-2.py
Normal file
39
0010-2.py
Normal file
@ -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
|
||||||
Loading…
Reference in New Issue
Block a user