Goldbach's comet: Difference between revisions

Line 626:
 
Instead, for G(1e6), we find all primes less than a million, subtract each from 1 million and count how many of the differences are prime and cut that in half. We cut that sum in half because this approach counts each pair twice (once with the smallest value first, again with the smallest value second -- since 1e6 is not the square of a prime we do not have a prime which appears twice in one of these sums).
 
=={{header|jq}}==
'''Works with jq and gojq, the C and Go implementations of jq.'''
 
'''Preliminaries'''
<syntaxhighlight lang=jq>
def count(s): reduce s as $_ (0; .+1);
 
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
 
def nwise($n):
def n: if length <= $n then . else .[0:$n] , (.[$n:] | n) end;
n;
 
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
($n | sqrt) as $rt
| 23
| until( . > $rt or ($n % . == 0); .+2)
| . > $rt
end;
</syntaxhighlight>
'''The Tasks'''
<syntaxhighlight lang=jq>
# emit nothing if . is odd
def G:
select(. % 2 == 0)
| count( range(2; (./2)+1) as $i
| select(($i|is_prime) and ((.-$i)|is_prime)) );
 
def task1:
"The first 100 G numbers:",
([range(4; 203; 2) | G] | nwise(10) | map(lpad(4)) | join(" "));
 
def task($n):
$n, 4, 22
|"G(\(.)): \(G)";
 
task1, "", task(1000000)
</syntaxhighlight>
{{output}}
<pre>
The first 100 G numbers:
1 1 1 2 1 2 2 2 2 3
3 3 2 3 2 4 4 2 3 4
3 4 5 4 3 5 3 4 6 3
5 6 2 5 6 5 5 7 4 5
8 5 4 9 4 5 7 3 6 8
5 6 8 6 7 10 6 6 12 4
5 10 3 7 9 6 5 8 7 8
11 6 5 12 4 8 11 5 8 10
5 6 13 9 6 11 7 7 14 6
8 13 5 8 11 7 9 13 8 9
 
G(1000000): 5402
G(4): 1
G(22): 3
</pre>
 
=={{header|Julia}}==
2,515

edits