Sum of two adjacent numbers are primes: Difference between revisions

→‎{{header|Python}}: Added a functionally composed variant.
(→‎{{header|ALGOL 68}}: Simplify as per the Phix sample)
(→‎{{header|Python}}: Added a functionally composed variant.)
Line 1,000:
 
=={{header|Python}}==
===Procedural===
<syntaxhighlight lang="python">#!/usr/bin/python
 
Line 1,044 ⟶ 1,045:
35 + 36 = 71
36 + 37 = 73</pre>
 
===Functional===
<syntaxhighlight lang="python">'''Prime sums of two consecutive integers'''
 
from itertools import chain, count, islice
 
 
# primeSumsOfTwoConsecutiveIntegers :: [Int]
def primeSumsOfTwoConsecutiveIntegers():
'''Infinite series of prime sums of
two consecutive integers.
'''
def go(a, b):
n = a + b
return [(n, (a, b))] if isPrime(n) else []
 
return chain.from_iterable(
map(go, count(1), count(2))
)
 
 
# ------------------------- TEST -------------------------
# main :: IO ()
def main():
'''First 20 prime sums of two consecutive integers.'''
print(
'\n'.join([
f'{n} = {a} + {b}' for n, (a, b) in islice(
primeSumsOfTwoConsecutiveIntegers(),
20
)
])
)
 
 
# ----------------------- GENERIC ------------------------
 
# isPrime :: Int -> Bool
def isPrime(n):
'''True if n is prime.'''
if n in (2, 3):
return True
if 2 > n or 0 == n % 2:
return False
if 9 > n:
return True
if 0 == n % 3:
return False
 
def p(x):
return 0 == n % x or 0 == n % (2 + x)
 
return not any(map(p, range(5, 1 + int(n ** 0.5), 6)))
 
 
# MAIN ---
if __name__ == '__main__':
main()</syntaxhighlight>
{{Out}}
<pre>3 = 1 + 2
5 = 2 + 3
7 = 3 + 4
11 = 5 + 6
13 = 6 + 7
17 = 8 + 9
19 = 9 + 10
23 = 11 + 12
29 = 14 + 15
31 = 15 + 16
37 = 18 + 19
41 = 20 + 21
43 = 21 + 22
47 = 23 + 24
53 = 26 + 27
59 = 29 + 30
61 = 30 + 31
67 = 33 + 34
71 = 35 + 36
73 = 36 + 37</pre>
 
=={{header|Quackery}}==
9,655

edits