Prime triplets: Difference between revisions

Added Lua
(→‎J: faster alternatives)
(Added Lua)
Line 850:
[5477, 5479, 5483]
</pre>
=={{header|Lua}}==
<syntaxhighlight lang="lua">
do -- find primes p where p+2 and p+6 are also prime
local MAX_PRIME = 5500
local pList = {}
do -- set pList to a list of primes up to MAX_PRIME
-- sieve the odd primes to n and construct the list
local p = {}
for i = 3, MAX_PRIME, 2 do p[ i ] = true end
for i = 3, math.floor( math.sqrt( MAX_PRIME ) ), 2 do
if p[ i ] then
for s = i * i, MAX_PRIME, i + i do p[ s ] = false end
end
end
pList[ 1 ] = 2
for i = 3, MAX_PRIME, 2 do
if p[ i ] then pList[ #pList + 1 ] = i end
end
end
local function fmt ( n ) return string.format( "%4d", n ) end
io.write( "Prime triplets under ", MAX_PRIME, ":", "\n" )
local tCount = 0
for i = 1, #pList - 2 do
local p1, p2, p3 = pList[ i ], pList[ i + 1 ], pList[ i + 2 ]
if p2 - p1 == 2 and p3 - p2 == 4 then
tCount = tCount + 1
io.write( "[ ", fmt( p1 ), " ", fmt( p2 ), " ", fmt( p3 ), " ]"
, ( tCount % 5 == 0 and "\n" or " " )
)
end
end
io.write( "\n", "Found ", tCount, " prime triplets\n" )
end
</syntaxhighlight>
{{out}}
<pre>
Prime triplets under 5500:
[ 5 7 11 ] [ 11 13 17 ] [ 17 19 23 ] [ 41 43 47 ] [ 101 103 107 ]
[ 107 109 113 ] [ 191 193 197 ] [ 227 229 233 ] [ 311 313 317 ] [ 347 349 353 ]
[ 461 463 467 ] [ 641 643 647 ] [ 821 823 827 ] [ 857 859 863 ] [ 881 883 887 ]
[ 1091 1093 1097 ] [ 1277 1279 1283 ] [ 1301 1303 1307 ] [ 1427 1429 1433 ] [ 1481 1483 1487 ]
[ 1487 1489 1493 ] [ 1607 1609 1613 ] [ 1871 1873 1877 ] [ 1997 1999 2003 ] [ 2081 2083 2087 ]
[ 2237 2239 2243 ] [ 2267 2269 2273 ] [ 2657 2659 2663 ] [ 2687 2689 2693 ] [ 3251 3253 3257 ]
[ 3461 3463 3467 ] [ 3527 3529 3533 ] [ 3671 3673 3677 ] [ 3917 3919 3923 ] [ 4001 4003 4007 ]
[ 4127 4129 4133 ] [ 4517 4519 4523 ] [ 4637 4639 4643 ] [ 4787 4789 4793 ] [ 4931 4933 4937 ]
[ 4967 4969 4973 ] [ 5231 5233 5237 ] [ 5477 5479 5483 ]
Found 43 prime triplets</pre>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">Cases[Partition[Most@NestWhileList[NextPrime, 2, # < 5500 &], 3,
3,032

edits