Primes: n*2^m+1: Difference between revisions

Line 573:
 
(Most of the implementation here is about merging intermediate values and formatting for display. The calculation for m is <code>i.&1"1]1 p:1+(1+i.45) */ 2^i.9</code> -- for n in the range 1..45, try all m exponents in the range 0..8 and find the first m value for each n which corresponds to a prime.)
 
=={{header|jq}}==
{{works with|jq}}
'''Works with gojq, the Go implementation of jq.'''
gojq supports unbounded-precision integer arithmetic but the following
algorithm for prime number detection is not up to the stretch tasks.
<syntaxhighlight lang=jq>
# Input should be an integer
# No sqrt!
def isPrime:
. 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;
 
# Emit [m, n*2**m+1] where m is smallest non-negative integer such that n * 2**m + 1 is prime
# WARNING: continues searching ad infinitum ...
def n2m1:
. as $n
| first(
foreach range(0; infinite) as $m (null;
if . == null then 1 else 2*. end;
(. * $n + 1)
| select(isPrime) | [$m, .] ) ) ;
 
# The task:
"[N,M,Prime]\n------------------",
( range(1;45) | [.] + n2m1 )
</syntaxhighlight>
'''Invocation''': jq -nrc -f n2m1.jq
{{output}}
<pre>
[1,0,2]
[2,0,3]
[3,1,7]
[4,0,5]
[5,1,11]
[6,0,7]
[7,2,29]
[8,1,17]
[9,1,19]
[10,0,11]
[11,1,23]
[12,0,13]
[13,2,53]
[14,1,29]
[15,1,31]
[16,0,17]
[17,3,137]
[18,0,19]
[19,6,1217]
[20,1,41]
[21,1,43]
[22,0,23]
[23,1,47]
[24,2,97]
[25,2,101]
[26,1,53]
[27,2,109]
[28,0,29]
[29,1,59]
[30,0,31]
[31,8,7937]
[32,3,257]
[33,1,67]
[34,2,137]
[35,1,71]
[36,0,37]
[37,2,149]
[38,5,1217]
[39,1,79]
[40,0,41]
[41,1,83]
[42,0,43]
[43,2,173]
[44,1,89]
[45,2,181]
[46,0,47]
</pre>
 
=={{header|Julia}}==
2,442

edits