Factorial primes: Difference between revisions

Content added Content deleted
(Added Perl)
Line 135:
 
(i.28x here would have given us an eleventh prime, but the task asked for the first 10, and the stretch goal requires considerable patience.)
 
=={{header|jq}}==
The following jq program has been tested with both the C and Go implementations
of jq. The latter supports unbounded-precision arithmetic, but the former
has sufficient accuracy to compute the first 10 factorial primes.
However, the implementation of `is_prime` used here is not sufficiently
fast to compute more than the first 10 primes in a reasonable amount of time.
 
<syntaxhighlight lang="jq">
# The algorithm is quite fast because the state of `until` is just a number and we skip by 2 or 4
def is_prime:
. as $n
| if ($n < 2) then false
elif ($n % 2 == 0) then $n == 2
elif ($n % 3 == 0) then $n == 3
else 5
| until( . <= 0;
if .*. > $n then -1
elif ($n % . == 0) then 0
else . + 2
| if ($n % . == 0) then 0
else . + 4
end
end)
| . == -1
end;
 
def factorial_primes:
foreach range(1; infinite) as $i (1; . * $i;
if ((.-1) | is_prime) then [($i|tostring) + "! - 1 = ", .-1] else empty end,
if ((.+1) | is_prime) then [($i|tostring) + "! + 1 = ", .+1] else empty end ) ;
 
limit(20; factorial_primes)
| .[1] |= (tostring | (if length > 40 then .[:20] + " .. " + .[-20:] else . end))
| add
</syntaxhighlight>
Invocation: jq -nr -f factorial-primes.jq
{{output}}
<pre>
1! + 1 = 2
2! + 1 = 3
3! - 1 = 5
3! + 1 = 7
4! - 1 = 23
6! - 1 = 719
7! - 1 = 5039
11! + 1 = 39916801
12! - 1 = 479001599
14! - 1 = 87178291199
# terminated
</pre>
 
=={{header|Julia}}==