Additive primes: Difference between revisions

Content added Content deleted
(→‎{{header|REXX}}: added/changed whitespace and comments, optimized the program.)
Line 599: Line 599:
461 463 467 487
461 463 467 487
54 additive primes found.
</pre>

=={{header|jq}}==
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''

'''Preliminaries'''
<lang jq>def is_prime:
. as $n
| if ($n < 2) then false
elif ($n % 2 == 0) then $n == 2
elif ($n % 3 == 0) then $n == 3
elif ($n % 5 == 0) then $n == 5
elif ($n % 7 == 0) then $n == 7
elif ($n % 11 == 0) then $n == 11
elif ($n % 13 == 0) then $n == 13
elif ($n % 17 == 0) then $n == 17
elif ($n % 19 == 0) then $n == 19
else {i:23}
| until( (.i * .i) > $n or ($n % .i == 0); .i += 2)
| .i * .i > $n
end;

# Emit an array of primes less than `.`
def primes:
if . < 2 then []
else [2] + [range(3; .; 2) | select(is_prime)]
end;

def add(s): reduce s as $x (null; . + $x);

def sumdigits: add(tostring | explode[] | [.] | implode | tonumber);

# Pretty-printing
def nwise($n):
def n: if length <= $n then . else .[0:$n] , (.[$n:] | n) end;
n;

def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
</lang>
'''The task'''
<lang jq>
# Input: a number n
# Output: an array of additive primes less than n
def additive_primes:
primes
| . as $primes
| reduce .[] as $p (null;
( $p | sumdigits ) as $sum
| if (($primes | bsearch($sum)) > -1)
then . + [$p]
else .
end );

"Erdős primes under 500:",
(500 | additive_primes
| ((nwise(10) | map(lpad(4)) | join(" ")),
"\n\(length) additive primes found."))
</lang>
{{out}}
<pre>
Erdős primes under 500:
2 3 5 7 11 23 29 41 43 47
61 67 83 89 101 113 131 137 139 151
157 173 179 191 193 197 199 223 227 229
241 263 269 281 283 311 313 317 331 337
353 359 373 379 397 401 409 421 443 449
461 463 467 487

54 additive primes found.
54 additive primes found.
</pre>
</pre>