Ulam spiral (for primes): Difference between revisions

m (→‎{{header|Phix}}: is_prime() now a builtin)
Line 2,681:
Ulam.generate(9)
}</lang>
 
=={{header|Lua}}==
<lang lua>function ulamspiral(n, f)
print("n = " .. n)
local function xyn(x, y, n)
if n%2==1 then x, y = n-1-x, n-1-y end
local m = math.min(x, y, n-1-x, n-1-y)
return x<y and (n-2*m-2)^2+(x-m)+(y-m) or (n-2*m)^2-(x-m)-(y-m)
end
for y = 0, n-1 do
for x = 0, n-1 do
io.write(f(xyn(x,y,n)))
end
print()
end
print()
end
 
local function isprime(n)
if n < 2 then return false end
if n % 2 == 0 then return n==2 end
if n % 3 == 0 then return n==3 end
local limit = math.sqrt(n)
for f = 5, limit, 6 do
if n % f == 0 or n % (f+2) == 0 then return false end
end
return true
end
 
ulamspiral(6, function(z) return isprime(z) and string.format("[%2d]",z) or string.format(" %2d ",z) end)
ulamspiral(10, function(z) return isprime(z) and string.format("%2d ",z) or " . " end)
ulamspiral(15, function(z) return isprime(z) and string.format("* ",z) or " " end)
ulamspiral(21, function(z) return isprime(z) and "██" or " " end)</lang>
{{out}}
<pre>n = 6
36 35 34 33 32 [31]
[17] 16 15 14 [13] 30
18 [ 5] 4 [ 3] 12 [29]
[19] 6 1 [ 2][11] 28
20 [ 7] 8 9 10 27
21 22 [23] 24 25 26
 
n = 10
. . . 97 . . . . . .
. . . . 61 . 59 . . .
. 37 . . . . . 31 . 89
67 . 17 . . . 13 . . .
. . . 5 . 3 . 29 . .
. . 19 . . 2 11 . 53 .
. 41 . 7 . . . . . .
71 . . . 23 . . . . .
. 43 . . . 47 . . . 83
73 . . . . . 79 . . .
 
n = 15
* * *
* *
* * * *
* * *
* * * * *
* * * *
* * *
* * * * * *
* * *
* *
* * * * *
* *
*
* * *
* *
 
n = 21
██ ██ ██ ██
██ ██ ██ ██
██ ██ ██ ██
██ ██ ██
██ ██ ██
██ ██ ██ ██
██ ██ ██
██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██
██ ██ ██
██ ██ ████ ██ ██ ██
██ ██ ██
██ ██
██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██
██ ██
██ ██ ██ ██ ██
██ ██
██ ██ ██ ██
██ ██ ██ ██
██ ██ ██ ██</pre>
 
=={{header|PARI/GP}}==
Anonymous user