Jump to content

Summation of primes: Difference between revisions

m
→‎Python :: Functional: Fractionally faster series of primes
(→‎Python :: Functional: Added a more efficient variant (defined over a generator of primes))
m (→‎Python :: Functional: Fractionally faster series of primes)
Line 414:
<lang python>'''Summatiom of primes'''
 
from itertools import count, takewhile
 
 
Line 433:
 
# ----------------------- GENERIC ------------------------
 
# enumFromThen :: Int -> Int -> [Int]
def enumFromThen(m):
'''A non-finite stream of integers
starting at m, and continuing
at the interval between m and n.
'''
return lambda n: count(m, n - m)
 
 
# primes :: [Int]
def primes():
'''An Noninfinite finite sequencestream of prime numbersprimes.'''
'''seen = {}
n =yield 2
dctp = {}None
for q in enumFromThen(3)(5):
while True:
ifp n= inseen.pop(q, dct:None)
forif p inis dct[n]None:
seen[q ** 2] = dct.setdefault(n + p, []).append(p)q
delyield dct[n]q
else:
yield nseen[
dct[n * n] = [n]until(
n = 1 + n lambda x: x not in seen,
lambda x: x + 2 * p,
q + 2 * p
)
] = p
 
 
# until :: (a -> Bool) -> (a -> a) -> a -> a
def until(p, f, v):
'''The result of repeatedly applying f until p holds.
The initial seed value is x.
'''
while Truenot p(v):
v = f(v)
return v
 
 
9,655

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.