Ramanujan primes: Difference between revisions
Content added Content deleted
m (→{{header|Wren}}: Wren-trait -> Wren-iterate) |
|||
Line 393: | Line 393: | ||
Elapsed time: 187.2 milliseconds |
Elapsed time: 187.2 milliseconds |
||
</pre> |
|||
=={{header|jq}}== |
|||
'''Adapted from [[#Wren|Wren]]''' |
|||
{{works with|jq}} |
|||
<syntaxhighlight lang=jq> |
|||
def lpad($len): tostring | ($len - length) as $l | (" " * $l) + .; |
|||
# tabular print |
|||
def tprint(columns; wide): |
|||
reduce _nwise(columns) as $row (""; |
|||
. + ($row|map(lpad(wide)) | join(" ")) + "\n" ); |
|||
# output: {count} |
|||
def primeCounter($limit): |
|||
{count: [range(0; $limit) | 1] } |
|||
| if ($limit > 0) then .count[0] = 0 else . end |
|||
| if ($limit > 1) then .count[1] = 0 else . end |
|||
| .count |= reduce range(4; $limit; 2) as $i (.; .[$i] = 0) |
|||
| .p = 3 |
|||
| .sq = 9 |
|||
| until(.sq >= $limit; |
|||
if (.count[.p] != 0) |
|||
then .q = .sq |
|||
| until (.q >= $limit; |
|||
.count[.q] = 0 |
|||
| .q += (.p * 2) ) |
|||
else . |
|||
end |
|||
| .sq += ((.p + 1) * 4) |
|||
| .p += 2 ) |
|||
| .sum = 0 |
|||
| reduce range(0; $limit) as $i (.; |
|||
.sum += .count[$i] |
|||
| .count[$i] = .sum ) ; |
|||
# input: {count} |
|||
def primeCount($n): if $n < 1 then 0 else .count[$n] end; |
|||
# 2n ln 2n < Rn < 4n ln 4n |
|||
def ramanujanMax(n): (4 * n * ((4*n)|log))|ceil; |
|||
# input: {count} |
|||
def ramanujanPrime($n): |
|||
if ($n == 1) then 2 |
|||
else first( foreach range(ramanujanMax($n); 1+2*$n; -1) as $i (.emit=null; |
|||
if ($i % 2 == 1) then . |
|||
elif (primeCount($i) - primeCount(($i/2)|floor) < $n) then .emit=$i + 1 |
|||
else . |
|||
end) |
|||
| select(.emit).emit ) // 0 |
|||
end ; |
|||
# The tasks |
|||
primeCounter(1 + ramanujanMax(1e6)) |
|||
| "The first 100 Ramanujan primes are:", |
|||
( [range(1;101) as $i | ramanujanPrime($i) ] |
|||
| tprint(10; 5) ), |
|||
"\nThe 1,000th Ramanujan prime is \(ramanujanPrime(1000))", |
|||
"\nThe 10,000th Ramanujan prime is \(ramanujanPrime(10000))", |
|||
"\nThe 100,000th Ramanujan prime is \(ramanujanPrime(100000))", |
|||
"\nThe 1,000,000th Ramanujan prime is \(ramanujanPrime(1000000))" |
|||
</syntaxhighlight> |
|||
{{output}} |
|||
<pre> |
|||
The first 100 Ramanujan primes are: |
|||
2 11 17 29 41 47 59 67 71 97 |
|||
101 107 127 149 151 167 179 181 227 229 |
|||
233 239 241 263 269 281 307 311 347 349 |
|||
367 373 401 409 419 431 433 439 461 487 |
|||
491 503 569 571 587 593 599 601 607 641 |
|||
643 647 653 659 677 719 727 739 751 769 |
|||
809 821 823 827 853 857 881 937 941 947 |
|||
967 983 1009 1019 1021 1031 1049 1051 1061 1063 |
|||
1087 1091 1097 1103 1151 1163 1187 1217 1229 1249 |
|||
1277 1289 1297 1301 1367 1373 1423 1427 1429 1439 |
|||
The 1,000th Ramanujan prime is 19403 |
|||
The 10,000th Ramanujan prime is 242057 |
|||
The 100,000th Ramanujan prime is 2916539 |
|||
The 1,000,000th Ramanujan prime is 34072993 |
|||
</pre> |
</pre> |
||