Successive prime differences: Difference between revisions

(→‎{{header|J}}: align naming to task)
Line 1,375:
Number found = 306</pre>
 
=={{header|jq}}==
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
 
For a suitable implementation of `is_prime` as used here, see e.g. # [[Erd%C5%91s-primes#jq]].
<lang jq># Emit a stream of consecutive primes.
# The stream is unbounded if . is null or infinite,
# otherwise it continues up to but excluding `.`.
def primes:
(if . == null then infinite else . end) as $n
| 2, (range(3; $n; 2) | select(is_prime));
 
# s is a stream
# $deltas is an array
# Output: a stream of arrays, each corresponding to a selection of consecutive
# items from s satisfying the differences requirement.
def filter_differences(s; $deltas):
 
def diffs_equal: # i.e. equal to $deltas
. as $in
| all( range(1;length);
($in[.] - $in[.-1]) == $deltas[. - 1]);
 
($deltas|length + 1) as $n
| foreach s as $x ( {};
.emit = null
| .tuple += [$x]
| .tuple |= .[-$n:]
| if (.tuple|length) == $n
then if (.tuple|diffs_equal) then .emit = .tuple
else .
end
else .
end;
select(.emit).emit );
 
def report_first_last_count(s):
null | {first,last,count}
| reduce s as $x (.;
if .first == null then .first = $x else . end
| .count = .count + 1
| .last = $x ) ;
</lang>
'''The Tasks'''
<lang jq>[pow(10;6) | primes] as $p1e6
| ([2], [1], [2,2], [2,4], [4,2], [6,4,2]) as $d
| ("\nFor deltas = \($d):", report_first_last_count(filter_differences($p1e6[]; $d ) ) )</lang>
{{out}}
<pre>
For deltas = [2]:
{"first":[3,5],"last":[999959,999961],"count":8169}
 
For deltas = [1]:
{"first":[2,3],"last":[2,3],"count":1}
 
For deltas = [2,2]:
{"first":[3,5,7],"last":[3,5,7],"count":1}
 
For deltas = [2,4]:
{"first":[5,7,11],"last":[999431,999433,999437],"count":1393}
 
For deltas = [4,2]:
{"first":[7,11,13],"last":[997807,997811,997813],"count":1444}
 
For deltas = [6,4,2]:
{"first":[31,37,41,43],"last":[997141,997147,997151,997153],"count":306}
</pre>
=={{header|Julia}}==
<lang julia>using Primes
2,498

edits