Summation of primes: Difference between revisions
Content added Content deleted
(→Python :: Functional: Added a more efficient variant (defined over a generator of primes)) |
m (→Python :: Functional: Fractionally faster series of primes) |
||
Line 414: | Line 414: | ||
<lang python>'''Summatiom of primes''' |
<lang python>'''Summatiom of primes''' |
||
from itertools import takewhile |
from itertools import count, takewhile |
||
Line 433: | Line 433: | ||
# ----------------------- GENERIC ------------------------ |
# ----------------------- 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] |
# primes :: [Int] |
||
def primes(): |
def primes(): |
||
''' |
'''An infinite stream of primes.''' |
||
seen = {} |
|||
yield 2 |
|||
p = None |
|||
for q in enumFromThen(3)(5): |
|||
⚫ | |||
p = seen.pop(q, None) |
|||
if p is None: |
|||
seen[q ** 2] = q |
|||
yield q |
|||
else: |
else: |
||
seen[ |
|||
until( |
|||
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. |
|||
''' |
|||
⚫ | |||
v = f(v) |
|||
return v |
|||