Ulam spiral (for primes): Difference between revisions

m
(Kotlin: nothing field removed)
m (→‎{{header|Wren}}: Minor tidy)
 
(131 intermediate revisions by 42 users not shown)
Line 1:
{{task|Prime Numbers}}
 
An Ulam spiral (of primes numbers) is a method of visualizing prime numbersprimes when expressed in a (normally counter-clockwise) outward spiral (usually starting at <big>'''1'''</big>), &nbsp; constructed on a square grid, starting at the "center".
 
An Ulam spiral is also known as a &nbsp; ''prime spiral''.
 
The first grid (green) is shown with allsequential numbersintegers, (primes and non-primes) shown,&nbsp; starting at &nbsp; <big>'''1'''</big>.
 
In an Ulam spiral of primes, only the primes are shown (usually indicated by some glyph such as a dot or asterisk), &nbsp; and all non-primes as shown as a blank &nbsp; (or some other whitespace). Of course, the grid and border are not to be displayed (but they are displayed here when using these Wiki HTML tables).
 
Of course, the grid and border are not to be displayed (but they are displayed here when using these Wiki HTML tables).
Normally, the spiral starts in the "center", and the 2<sup>nd</sup> number is to the viewer's right and the number spiral starts from there in a counter-clockwise direction. There are other geometric shapes that are used as well, including clock-wise spirals. Also, some spirals (for the 2<sup>nd</sup> number) is viewed upwards from the 1<sup>st</sup> number instead of to the right, but that is just a matter of orientation.
 
Normally, the spiral starts in the "center", &nbsp; and the &nbsp; 2<sup>nd</sup> &nbsp; number is to the viewer's right and the number spiral starts from there in a counter-clockwise direction.
 
There are other geometric shapes that are used as well, including clock-wise spirals.
 
Also, some spirals (for the &nbsp; 2<sup>nd</sup> &nbsp; number) &nbsp; is viewed upwards from the &nbsp; 1<sup>st</sup> &nbsp; number instead of to the right, but that is just a matter of orientation.
 
Sometimes, the starting number can be specified to show more visual striking patterns (of prime densities).
 
[A larger than necessary grid (numbers wise) is shown here to illustrate the pattern of numbers on the diagonals &nbsp; (which may be used by the method to orientate the direction of spiral-construction algorithm within the example computer programs)].
 
Then, in the next phase in the transformation of the Ulam prime spiral, &nbsp; the non-primes are translated to blanks.
 
In the orange grid below, &nbsp; the primes are left intact, &nbsp; and all non-primes are changed to blanks.
{| class="wikitable" style="float:center;border: 4px solid blue; background:lightgreen; color:black; margin-left:auto;margin-right:auto;text-align:center;width:34em;height:34em;table-layout:fixed;font-size:125%"
 
Then, in the final transformation of the Ulam spiral (the yellow grid), &nbsp; translate the primes to a glyph such as a &nbsp; <big><big><b> &bull; </b></big></big> &nbsp; or some other suitable glyph.
<br>
 
{| class="wikitable" style="float:left;border: 2px solid black; background:lightgreen; color:black; margin-left:0;margin-right:auto;text-align:center;width:34em;height:34em;table-layout:fixed;font-size:70%"
|-
| <big><big>'''65'''</big></big> || <big><big>'''64'''</big></big> || <big><big>'''63'''</big></big> || <big><big>'''62'''</big></big> || <big><big>'''61'''</big></big> || <big><big>'''60'''</big></big> || <big><big>'''59'''</big></big> || <big><big>'''58'''</big></big> || <big><big>'''57'''</big></big>
Line 36 ⟶ 49:
|}
 
{| class="wikitable" style="float:left;border: 2px solid black; background:orange; color:black; margin-left:20px;margin-right:auto;text-align:center;width:34em;height:34em;table-layout:fixed;font-size:70%"
 
[A larger than necessary grid (numbers wise) is shown here to illustrate the pattern of numbers on the diagonals (which may be used by the method to orientate the direction of spiral-construction algorithm within the example computer programs)].
 
 
Then, to show the Ulam prime spiral, a character (or glyph) is shown instead of each prime number, and a blank for all non-prime numbers. In the orange grid below, the prime numbers are left intact to see what numbers are to be changed to the character for viewing.
 
 
 
{| class="wikitable" style="float:center;border: 4px solid blue; background:orange; color:black; margin-left:auto;margin-right:auto;text-align:center;width:34em;height:34em;table-layout:fixed;font-size:125%"
|-
| <big><big>''' '''</big></big> || <big><big>''' '''</big></big> || <big><big>''' '''</big></big> || <big><big>''' '''</big></big> || <big><big>'''61'''</big></big> || <big><big>''' '''</big></big> || <big><big>'''59'''</big></big> || <big><big>''' '''</big></big> || <big><big>''' '''</big></big>
Line 65 ⟶ 70:
|}
 
{| class="wikitable" style="float:left;border: 2px solid black; background:yellow; color:black; margin-left:20px;margin-right:auto;text-align:center;width:34em;height:34em;table-layout:fixed;font-size:70%"
 
 
Then, in the final transformation of the Ulam spiral (the yellow grid), translate the primes to a glyph such as a <big><big> ∙ </big></big> or some other suitable glyph.
 
{| class="wikitable" style="float:center;border: 4px solid blue; background:yellow; color:black; margin-left:auto;margin-right:auto;text-align:center;width:34em;height:34em;table-layout:fixed;font-size:125%"
|-
| <big><big>''' '''</big></big> || <big><big>''' '''</big></big> || <big><big>''' '''</big></big> || <big><big>''' '''</big></big> || <big><big>''' &bull;'''</big></big> || <big><big>''' '''</big></big> || <big><big>''' &bull;'''</big></big> || <big><big>''' '''</big></big> || <big><big>''' '''</big></big>
|-
| <big><big>''' '''</big></big> || <big><big>''' &bull;'''</big></big> || <big><big>''' '''</big></big> || <big><big>''' '''</big></big> || <big><big>''' '''</big></big> || <big><big>''' '''</big></big> || <big><big>''' '''</big></big> || <big><big>''' &bull;'''</big></big> || <big><big>''' '''</big></big>
|-
| <big><big>''' &bull;'''</big></big> || <big><big>''' '''</big></big> || <big><big>''' &bull;'''</big></big> || <big><big>''' '''</big></big> || <big><big>''' '''</big></big> || <big><big>''' '''</big></big> || <big><big>''' &bull;'''</big></big> || <big><big>''' '''</big></big> || <big><big>''' '''</big></big>
|-
| <big><big>''' '''</big></big> || <big><big>''' '''</big></big> || <big><big>''' '''</big></big> || <big><big>''' &bull;'''</big></big> || <big><big>''' '''</big></big> || <big><big>''' &bull;'''</big></big> || <big><big>''' '''</big></big> || <big><big>''' &bull;'''</big></big> || <big><big>''' '''</big></big>
|-
| <big><big>''' '''</big></big> || <big><big>''' '''</big></big> || <big><big>''' &bull;'''</big></big> || <big><big>''' '''</big></big> || <big><big>''' '''</big></big> || <big><big>''' &bull;'''</big></big> || <big><big>''' &bull;'''</big></big> || <big><big>''' '''</big></big> || <big><big>''' &bull;'''</big></big>
|-
| <big><big>''' '''</big></big> || <big><big>''' &bull;'''</big></big> || <big><big>''' '''</big></big> || <big><big>''' &bull;'''</big></big> || <big><big>''' '''</big></big> || <big><big>''' '''</big></big> || <big><big>''' '''</big></big> || <big><big>''' '''</big></big> || <big><big>''' '''</big></big>
|-
| <big><big>''' &bull;'''</big></big> || <big><big>''' '''</big></big> || <big><big>''' '''</big></big> || <big><big>''' '''</big></big> || <big><big>''' &bull;'''</big></big> || <big><big>''' '''</big></big> || <big><big>''' '''</big></big> || <big><big>''' '''</big></big> || <big><big>''' '''</big></big>
|-
| <big><big>''' '''</big></big> || <big><big>''' &bull;'''</big></big> || <big><big>''' '''</big></big> || <big><big>''' '''</big></big> || <big><big>''' '''</big></big> || <big><big>''' &bull;'''</big></big> || <big><big>''' '''</big></big> || <big><big>''' '''</big></big> || <big><big>''' '''</big></big>
|-
| <big><big>''' &bull;'''</big></big> || <big><big>''' '''</big></big> || <big><big>''' '''</big></big> || <big><big>''' '''</big></big> || <big><big>''' '''</big></big> || <big><big>''' '''</big></big> || <big><big>''' &bull;'''</big></big> || <big><big>''' '''</big></big> || <big><big>''' '''</big></big>
|}
 
 
<br style="clear:both">
;Task
The Ulam spiral becomes more visually obvious as the grid increases in size.
 
 
For any sized '''N x N''' grid, construct and show an Ulam spiral (counter-clockwise) of primes starting at some specified initial number (the default would be '''1'''), with some suitably dotty representation to indicate primes, and the absence of dots to indicate non-primes.
;Task
For any sized &nbsp; <big>'''N &times; N'''</big> &nbsp; grid, &nbsp; construct and show an Ulam spiral (counter-clockwise) of primes starting at some specified initial number &nbsp; (the default would be '''1'''), &nbsp; with some suitably &nbsp; ''dotty'' &nbsp; (glyph) representation to indicate primes, &nbsp; and the absence of dots to indicate non-primes.
 
You should demonstrate the generator by showing at Ulam prime spiral large enough to (almost) fill your terminal screen.
 
;Also see:
::* Wikipedia entry: [http://en.wikipedia.org/wiki/Ulam_spiral Ulam spiral].
::* MathWorld&trade; entry: [http://mathworld.wolfram.com/PrimeSpiral.html Prime Spiral].
 
;Related tasks:
* &nbsp; [[Spiral matrix]]
* &nbsp; [[Zig-zag matrix]]
* &nbsp; [[Identity matrix]]
* &nbsp; [[Sequence of primes by Trial Division]]
 
 
;See also
* Wikipedia entry: &nbsp; [http://en.wikipedia.org/wiki/Ulam_spiral Ulam spiral]
* MathWorld&trade; entry: &nbsp; [http://mathworld.wolfram.com/PrimeSpiral.html Prime Spiral]
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">F cell(n, =x, =y, start = 1)
V d = 0
y = y - n I/ 2
x = x - (n - 1) I/ 2
V l = 2 * max(abs(x), abs(y))
d = I y >= x {(l * 3 + x + y)} E (l - x - y)
R (l - 1) ^ 2 + d + start - 1
 
F show_spiral(n, symbol = ‘# ’, start = 1, =space = ‘’)
V top = start + n * n + 1
V is_prime = [0B, 0B, 1B] [+] [1B, 0B] * (top I/ 2)
L(x) 3 .< 1 + Int(sqrt(top))
I !is_prime[x]
L.continue
L(i) (x * x .< top).step(x * 2)
is_prime[i] = 0B
 
(Int -> String) f = _ -> @symbol
 
I space == ‘’
space = ‘ ’ * symbol.len
 
I symbol.empty
V max_str = String(n * n + start - 1).len
I space == ‘’
space = (‘.’ * max_str)‘ ’
f = x -> String(x).rjust(@max_str)‘ ’
 
V cell_str = x -> I @is_prime[x] {@f(x)} E @space
 
L(y) 0 .< n
print((0 .< n).map(x -> cell(@n, x, @y, @start)).map(v -> @cell_str(v)).join(‘’))
print()
 
show_spiral(10, symbol' ‘# ’, space' ‘ ’)
show_spiral(9, symbol' ‘’, space' ‘ - ’)</syntaxhighlight>
 
{{out}}
<pre>
#
# #
# # #
# # #
# # #
# # # #
# #
# #
# # #
# #
 
- - - - 61 - 59 - -
- 37 - - - - - 31 -
67 - 17 - - - 13 - -
- - - 5 - 3 - 29 -
- - 19 - - 2 11 - 53
- 41 - 7 - - - - -
71 - - - 23 - - - -
- 43 - - - 47 - - -
73 - - - - - 79 - -
</pre>
 
=={{header|360 Assembly}}==
{{trans|Fortran}}
Compacted and optimized solution.
<syntaxhighlight lang="360asm">* Ulam spiral 26/04/2016
ULAM CSECT
USING ULAM,R13 set base register
SAVEAREA B STM-SAVEAREA(R15) skip savearea
DC 17F'0' savearea
STM STM R14,R12,12(R13) prolog
ST R13,4(R15) save previous SA
ST R15,8(R13) linkage in previous SA
LR R13,R15 establish addressability
LA R5,1 n=1
LH R8,NSIZE x=nsize
SRA R8,1
LA R8,1(R8) x=nsize/2+1
LR R9,R8 y=x
LR R1,R5 n
BAL R14,ISPRIME
C R0,=F'1' if isprime(n)
BNE NPRMJ0
BAL R14,SPIRALO spiral(x,y)=o
NPRMJ0 LA R5,1(R5) n=n+1
LA R6,1 i=1
LOOPI1 LH R2,NSIZE do i=1 to nsize-1 by 2
BCTR R2,0
CR R6,R2 if i>nsize-1
BH ELOOPI1
LR R7,R6 j=i; do j=1 to i
LOOPJ1 LA R8,1(R8) x=x+1
LR R1,R5 n
BAL R14,ISPRIME
C R0,=F'1' if isprime(n)
BNE NPRMJ1
BAL R14,SPIRALO spiral(x,y)=o
NPRMJ1 LA R5,1(R5) n=n+1
BCT R7,LOOPJ1 next j
ELOOPJ1 LR R7,R6 j=i; do j=1 to i
LOOPJ2 BCTR R9,0 y=y-1
LR R1,R5 n
BAL R14,ISPRIME
C R0,=F'1' if isprime(n)
BNE NPRMJ2
BAL R14,SPIRALO spiral(x,y)=o
NPRMJ2 LA R5,1(R5) n=n+1
BCT R7,LOOPJ2 next j
ELOOPJ2 LR R7,R6 j=i
LA R7,1(R7) j=i+1; do j=1 to i+1
LOOPJ3 BCTR R8,0 x=x-1
LR R1,R5 n
BAL R14,ISPRIME
C R0,=F'1' if isprime(n)
BNE NPRMJ3
BAL R14,SPIRALO spiral(x,y)=o
NPRMJ3 LA R5,1(R5) n=n+1
BCT R7,LOOPJ3 next j
ELOOPJ3 LR R7,R6 j=i
LA R7,1(R7) j=i+1; do j=1 to i+1
LOOPJ4 LA R9,1(R9) y=y+1
LR R1,R5 n
BAL R14,ISPRIME
C R0,=F'1' if isprime(n)
BNE NPRMJ4
BAL R14,SPIRALO spiral(x,y)=o
NPRMJ4 LA R5,1(R5) n=n+1
BCT R7,LOOPJ4 next j
ELOOPJ4 LA R6,2(R6) i=i+2
B LOOPI1
ELOOPI1 LH R7,NSIZE j=nsize
BCTR R7,0 j=nsize-1; do j=1 to nsize-1
LOOPJ5 LA R8,1(R8) x=x+1
LR R1,R5 n
BAL R14,ISPRIME
C R0,=F'1' if isprime(n)
BNE NPRMJ5
BAL R14,SPIRALO spiral(x,y)=o
NPRMJ5 LA R5,1(R5) n=n+1
BCT R7,LOOPJ5 next j
ELOOPJ5 LA R6,1 i=1
LOOPI2 CH R6,NSIZE do i=1 to nsize
BH ELOOPI2
LA R10,PG reset buffer
LA R7,1 j=1
LOOPJ6 CH R7,NSIZE do j=1 to nsize
BH ELOOPJ6
LR R1,R7 j
BCTR R1,0 (j-1)
MH R1,NSIZE (j-1)*nsize
AR R1,R6 r1=(j-1)*nsize+i
LA R14,SPIRAL-1(R1) @spiral(j,i)
MVC 0(1,R10),0(R14) output spiral(j,i)
LA R10,1(R10) pgi=pgi+1
LA R7,1(R7) j=j+1
B LOOPJ6
ELOOPJ6 XPRNT PG,80 print
LA R6,1(R6) i=i+1
B LOOPI2
ELOOPI2 L R13,4(0,R13) reset previous SA
LM R14,R12,12(R13) restore previous env
XR R15,R15 set return code
BR R14 call back
ISPRIME CNOP 0,4 ---------- isprime function
C R1,=F'2' if nn=2
BNE NOT2
LA R0,1 rr=1
B ELOOPII
NOT2 C R1,=F'2' if nn<2
BL RRZERO
LR R2,R1 nn
LA R4,2 2
SRDA R2,32 shift
DR R2,R4 nn/2
C R2,=F'0' if nn//2=0
BNE TAGII
RRZERO SR R0,R0 rr=0
B ELOOPII
TAGII LA R0,1 rr=1
LA R4,3 ii=3
LOOPII LR R3,R4 ii
MR R2,R4 ii*ii
CR R3,R1 if ii*ii<=nn
BH ELOOPII
LR R3,R1 nn
LA R2,0 clear
DR R2,R4 nn/ii
LTR R2,R2 if nn//ii=0
BNZ NEXTII
SR R0,R0 rr=0
B ELOOPII
NEXTII LA R4,2(R4) ii=ii+2
B LOOPII
ELOOPII BR R14 ---------- end isprime return rr
SPIRALO CNOP 0,4 ---------- spiralo subroutine
LR R1,R8 x
BCTR R1,0 x-1
MH R1,NSIZE (x-1)*nsize
AR R1,R9 r1=(x-1)*nsize+y
LA R10,SPIRAL-1(R1) r10=@spiral(x,y)
MVC 0(1,R10),O spiral(x,y)=o
BR R14 ---------- end spiralo
NS EQU 79 4n+1
NSIZE DC AL2(NS) =H'ns'
O DC CL1'*' if prime
PG DC CL80' ' buffer
LTORG
SPIRAL DC (NS*NS)CL1' '
YREGS
END ULAM</syntaxhighlight>
{{out}}
<pre>
* * * *
* * *
* * *
* * *
* * * *
* * *
* * * * * *
* * * * *
* * *
* * ** * * *
* * *
* *
* * * * * *
* * * *
* *
* * * * *
* *
* * *
* * * *
</pre>
 
=={{header|Ada}}==
Line 108 ⟶ 354:
The specification of package generic_ulam is as follows:
 
<langsyntaxhighlight Adalang="ada">generic
Size: Positive;
-- determines the size of the square
Line 126 ⟶ 372:
-- and New_Line N times
end Generic_Ulam;</langsyntaxhighlight>
 
Here is the implementation:
<langsyntaxhighlight Adalang="ada">package body Generic_Ulam is
subtype Index is Natural range 0 .. Size-1;
Line 164 ⟶ 410:
end Print_Spiral;
end Generic_Ulam;</langsyntaxhighlight>
 
The folowing implementation prints a 29*29 spiral with the primes represented as numbers, and a 10*10 spiral with the primes as boxes. It uses the generic function Prime_Numbers.Is_Prime, as specified in [[Prime decomposition#Ada]].
 
<langsyntaxhighlight Adalang="ada">with Generic_Ulam, Ada.Text_IO, Prime_Numbers;
 
procedure Ulam is
Line 194 ⟶ 440:
NL;
Visual.Print_Spiral;
end Ulam;</langsyntaxhighlight>
 
{{out}}
Line 238 ⟶ 484:
<> <> <>
<> <> </pre>
 
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
<syntaxhighlight lang="algol68">
BEGIN # construct a Ulam spiral for primes #
PR read "primes.incl.a68" PR # include prime utilities #
# prints a Ulam spiral for primes with the specified width, #
# starting from init. Primes will be indicated by prime char and #
# non-primes by composite char. The center of the spiral will be #
# indicated by center char - unless the center value is prime #
PROC print ulam spiral for primes = ( INT width, init, CHAR prime char, composite char, center char )VOID:
IF width >= 1 THEN
INT n = IF ODD width THEN width ELSE width + 1 FI;
[]BOOL prime = PRIMESIEVE ( init + ( n * n ) );
[ 1 : n, 1 : n ]CHAR spiral; FOR i TO n DO FOR j TO n DO spiral[ i, j ] := "_" OD OD;
INT y := ( n + 1 ) OVER 2;
INT x := y;
INT v := init;
spiral[ x, y ] := IF prime[ init ] THEN prime char ELSE center char FI;
INT w := 0;
WHILE x < 1 UPB spiral DO
w +:= 2;
x +:= 1;
y +:= 1;
FOR i TO w DO # right edge #
spiral[ x, y -:= 1 ] := IF prime[ v +:= 1 ] THEN prime char ELSE composite char FI
OD;
FOR i TO w DO # top edge #
spiral[ x -:= 1, y ] := IF prime[ v +:= 1 ] THEN prime char ELSE composite char FI
OD;
FOR i TO w DO # left edge #
spiral[ x, y +:= 1 ] := IF prime[ v +:= 1 ] THEN prime char ELSE composite char FI
OD;
FOR i TO w DO # bottom edge #
spiral[ x +:= 1, y ] := IF prime[ v +:= 1 ] THEN prime char ELSE composite char FI
OD
OD;
FOR v pos TO width DO
FOR h pos TO width DO
print( ( spiral[ h pos, v pos ] ) )
OD;
print( ( newline ) )
OD
FI # ulam spiral for primes # ;
 
print ulam spiral for primes( 35, 1, "#", " ", "+" )
END
</syntaxhighlight>
{{out}}
<pre>
# # # #
# # # # #
# # # #
# # # # #
# # # # #
# # # # # #
# # # # #
# # # # #
# # # # # # # #
# # # # # #
# # # # #
# # # # #
# # # # # # # #
# # #
# # # # # # # # # #
# # # # # # # # # #
# # # #
# # +## # # # # # #
# # # #
# #
# # # # # # # # # # #
# # # # # # #
# #
# # # # # #
# # # # #
# # # # #
# # # # # #
# # # # # # # # #
# # # #
# # # # # #
# # # # # #
# # # # #
# # # # #
# # # #
# # # # #
</pre>
 
=={{header|C}}==
<syntaxhighlight lang="c">
<lang c>
#include <stdio.h>
#include <stdint.h>
Line 279 ⟶ 611:
int mx = abs(x), my = abs(y);
int l = 2 * max(mx, my);
int d = y >= x ? l * 3 + x + y : l - x - y;
 
return pow(l - 1, 2) + d;
Line 328 ⟶ 660:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
Run with a side-length of 29
Line 394 ⟶ 726:
 
The following shows a spiral that's not necessarily square, which has questionable merit:
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
 
Line 423 ⟶ 755:
}
return 0;
}</langsyntaxhighlight>
 
=={{header|C++}}==
=== parametric version ===
<lang cpp>
<syntaxhighlight lang="cpp">#include <math.hcmath>
#include <iostream>
#include <string>
Line 527 ⟶ 859:
ulam.display( '#' );
return 0;
}</syntaxhighlight>
}
</lang>
{{out}}
<pre>
Line 576 ⟶ 907:
# # # # #
# # # #
# # # # #</pre>
 
=== generic version ===
ulam.hpp
<syntaxhighlight lang="cpp">#pragma once
 
#include <cmath>
#include <sstream>
#include <iomanip>
 
inline bool is_prime(unsigned a) {
if (a == 2) return true;
if (a <= 1 || a % 2 == 0) return false;
const unsigned max(std::sqrt(a));
for (unsigned n = 3; n <= max; n += 2) if (a % n == 0) return false;
return true;
}
 
enum direction { RIGHT, UP, LEFT, DOWN };
const char* N = " ---";
 
template<const unsigned SIZE>
class Ulam
{
public:
Ulam(unsigned start = 1, const char c = '\0') {
direction dir = RIGHT;
unsigned y = SIZE / 2;
unsigned x = SIZE % 2 == 0 ? y - 1 : y; // shift left for even n's
for (unsigned j = start; j <= SIZE * SIZE - 1 + start; j++) {
if (is_prime(j)) {
std::ostringstream os("");
if (c == '\0') os << std::setw(4) << j;
else os << " " << c << ' ';
s[y][x] = os.str();
}
else s[y][x] = N;
 
switch (dir) {
case RIGHT : if (x <= SIZE - 1 && s[y - 1][x].empty() && j > start) { dir = UP; }; break;
case UP : if (s[y][x - 1].empty()) { dir = LEFT; }; break;
case LEFT : if (x == 0 || s[y + 1][x].empty()) { dir = DOWN; }; break;
case DOWN : if (s[y][x + 1].empty()) { dir = RIGHT; }; break;
}
 
switch (dir) {
case RIGHT : x += 1; break;
case UP : y -= 1; break;
case LEFT : x -= 1; break;
case DOWN : y += 1; break;
}
}
}
 
template<const unsigned S> friend std::ostream& operator <<(std::ostream&, const Ulam<S>&);
 
private:
std::string s[SIZE][SIZE];
};
 
template<const unsigned SIZE>
std::ostream& operator <<(std::ostream& os, const Ulam<SIZE>& u) {
for (unsigned i = 0; i < SIZE; i++) {
os << '[';
for (unsigned j = 0; j < SIZE; j++) os << u.s[i][j];
os << ']' << std::endl;
}
return os;
}</syntaxhighlight>
ulam.cpp
<syntaxhighlight lang="cpp">#include <cstdlib>
#include <iostream>
#include "ulam.hpp"
 
int main(const int argc, const char* argv[]) {
using namespace std;
 
cout << Ulam<9>() << endl;
const Ulam<9> v(1, '*');
cout << v << endl;
 
return EXIT_SUCCESS;
}</syntaxhighlight>
{{out}}
<pre>[ --- --- --- --- 61 --- 59 --- ---]
[ --- 37 --- --- --- --- --- 31 ---]
[ 67 --- 17 --- --- --- 13 --- ---]
[ --- --- --- 5 --- 3 --- 29 ---]
[ --- --- 19 --- --- 2 11 --- 53]
[ --- 41 --- 7 --- --- --- --- ---]
[ 71 --- --- --- 23 --- --- --- ---]
[ --- 43 --- --- --- 47 --- --- ---]
[ 73 --- --- --- --- --- 79 --- ---]
 
[ --- --- --- --- * --- * --- ---]
[ --- * --- --- --- --- --- * ---]
[ * --- * --- --- --- * --- ---]
[ --- --- --- * --- * --- * ---]
[ --- --- * --- --- * * --- * ]
[ --- * --- * --- --- --- --- ---]
[ * --- --- --- * --- --- --- ---]
[ --- * --- --- --- * --- --- ---]
[ * --- --- --- --- --- * --- ---]</pre>
 
=={{header|Common Lisp}}==
<syntaxhighlight lang="lisp">
(defun ulam-spiral (n)
(loop for a in (spiral n n (* n n)) do
(format t "~{~d~}~%" a)))
 
(defun spiral
(n m b &aux (row (loop for a below n
collect (if (primep (- b a))
'* '#\space))))
(if (= m 1) (list row)
(cons row (mapcar #'reverse
(apply #'mapcar #'list
(spiral (1- m) n
(- b n)))))))
(defun primep (n)
(when (> n 1) (loop for a from 2 to (isqrt n)
never (zerop (mod n a)))))
</syntaxhighlight>
 
{{out}}
<pre>
> (ulam-spiral 139)
* * * * * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * * * * * *
* * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * *
* * * * * * *
* * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * *
* * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * *
* * * * * * *
* * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * * * * * * ** * * * * * * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *
* * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * *
* * * * * * * * *
* * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * *
* * * * * * *
* * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * *
* * * * * * * * * * * * * * *
* * * * * * * * * * * * *
NIL
</pre>
 
=={{header|Crystal}}==
{{trans|Go}}
<syntaxhighlight lang="ruby">enum Direction
RIGHT
UP
LEFT
DOWN
end
 
def generate(n : Int32, i : Int32, c : Int32 | String)
s = Array.new(n) { Array.new(n) { "" } }
 
dir = Direction::RIGHT
y = n // 2
x = n % 2 == 0 ? y - 1 : y
 
j = 1
while j <= n * n - 1 + i
s[y][x] = is_prime(j) ? j.to_s : c.to_s
 
# printf "j: %s, x: %s, y: %s \n", j, x, y
 
case dir
when Direction::RIGHT
dir = Direction::UP if x <= n - 1 && s[y - 1][x] == "" && j > i
when Direction::UP
dir = Direction::LEFT if s[y][x - 1] == ""
when Direction::LEFT
dir = Direction::DOWN if x == 0 || s[y + 1][x] == ""
when Direction::DOWN
dir = Direction::RIGHT if s[y][x + 1] == ""
end
 
case dir
when Direction::RIGHT
x += 1
when Direction::UP
y -= 1
when Direction::LEFT
x -= 1
when Direction::DOWN
y += 1
end
 
j += 1
end
 
s.map(&.join("\t")).join("\n")
end
 
def is_prime(n : Int32) : Bool
return true if n == 2
return false if n % 2 == 0 || n < 1
 
i = 3
while i <= Math.sqrt(n)
return false if n % i == 0
i += 2
end
 
true
end
 
puts generate 7, 1, "*"
</syntaxhighlight>
 
{{out}}
<pre>
37 * * * * * 31
* 17 * * * 13 *
* * 5 * 3 * 29
* 19 * 1 2 11 *
41 * 7 * * * *
* * * 23 * * *
43 * * * 47 * *
</pre>
 
=={{header|D}}==
{{trans|python}}
<langsyntaxhighlight lang="d">import std.stdio, std.math, std.algorithm, std.array, std.range;
 
int cell(in int n, int x, int y, in int start=1) pure nothrow @safe @nogc {
Line 614 ⟶ 1,288:
void main() {
35.showSpiral;
}</langsyntaxhighlight>
{{out}}
<pre> # # # #
Line 654 ⟶ 1,328:
===Alternative Version===
This generates a PGM image, using the module from the Grayscale Image Task;
<langsyntaxhighlight lang="d">import std.stdio, std.math, std.algorithm, std.array, grayscale_image;
 
uint cell(in uint n, int x, int y, in uint start=1) pure nothrow @safe @nogc {
Line 686 ⟶ 1,360:
 
img.savePGM("ulam_spiral.pgm");
}</langsyntaxhighlight>
 
 
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
 
[[File:DelphiUlamPrimeSpiral.png|frame|none]]
 
 
<syntaxhighlight lang="Delphi">
 
 
 
 
procedure DrawMatrixPrimes(Image: TImage; Mat: TMatrix);
{Display spiral, only marking cells that contain prime numbers}
var X,Y: integer;
var S: string;
var Size,Step: integer;
var Off: TSize;
var R: TRect;
begin
{Calculate size of grid}
Size:=Min(Image.Width,Image.Height);
Step:=Size div Length(Mat);
{Draw border rectangle}
Image.Canvas.Brush.Color:=clGreen;
Image.Canvas.Pen.Width:=4;
Image.Canvas.Rectangle(2,2,Length(Mat)*Step,Length(Mat)*Step);
{Setup font}
Image.Canvas.Font.Name:='Arial';
Image.Canvas.Font.Style:=[fsBold];
Image.Canvas.Font.Size:=14;
{Draw grid}
Image.Canvas.Pen.Width:=1;
{Draw vertical lines}
for X:=0 to Length(Mat) do
begin
Image.Canvas.MoveTo(X*Step,0);
Image.Canvas.LineTo(X*Step,Step*Length(Mat));
end;
{Draw horizontal lines}
for Y:=0 to Length(Mat) do
begin
Image.Canvas.MoveTo(0,Y*Step);
Image.Canvas.LineTo(Step*Length(Mat),Y*Step);
end;
{Label cells that contain primes}
for Y:=0 to High(Mat[0]) do
for X:=0 to High(Mat) do
if IsPrime(trunc(Mat[X,Y])) then
begin
{Color cells}
R:=Rect((X*Step)+2,(Y*Step)+2,X*Step+Step,Y*Step+Step);
InflateRect(R,-1,-1);
Image.Canvas.Pen.Width:=4;
Image.Canvas.Pen.Color:=clBlue;
Image.Canvas.Brush.Color:=clLime;
Image.Canvas.Rectangle(R);
{Label cell}
S:=Format('%0.0f',[Mat[X,Y]]);
Off:=Image.Canvas.TextExtent(S);
Off.CX:=(Step-Off.CX) div 2;
Off.CY:=(Step-Off.CY) div 2;
Image.Canvas.TextOut(X*Step+Off.CX,Y*Step+Off.CY,S);
end;
Image.Invalidate;
end;
 
 
 
procedure MakeSqrSpiralMatrix(var Mat: TMatrix; MatSize: integer);
{Create a spiral matrix of specified size}
var Inx: integer;
var R: TRect;
 
 
 
procedure DoTopRect(Off1,Off2: integer);
{Do top part of rectangle}
var X,Y: integer;
begin
for X:=R.Left+Off1 to R.Right+Off2 do
begin
Mat[X,R.Top]:=Inx;
Dec(Inx);
end;
end;
 
procedure DoRightRect(Off1,Off2: integer);
{Do Right part of rectangle}
var X,Y: integer;
begin
for Y:=R.Top+Off1 to R.Bottom+Off2 do
begin
Mat[R.Right,Y]:=Inx;
Dec(Inx);
end;
end;
 
 
procedure DoBottomRect(Off1,Off2: integer);
{Do bottom part of rectangle}
var X,Y: integer;
begin
for X:= R.Right+Off1 downto R.Left+Off2 do
begin
Mat[X,R.Bottom]:=Inx;
Dec(Inx);
end;
end;
 
procedure DoLeftRect(Off1,Off2: integer);
{Do left part of rectangle}
var X,Y: integer;
begin
for Y:=R.Bottom+Off1 downto R.Top+Off2 do
begin
Mat[R.Left,Y]:=Inx;
Dec(Inx);
end;
end;
 
 
procedure DoRect(R: TRect; var Inx: integer);
{Create one rotation of spiral around the rectangle}
begin
{The orientation of spiral is based in the size}
if (MatSize and 1)=0 then
begin
{Handle even sizes}
DoTopRect(0,0);
DoRightRect(1,0);
DoBottomRect(-1,0);
DoLeftRect(-1,1);
end
else
begin
{Handle odd sizes}
DoBottomRect(0,0);
DoLeftRect(-1,0);
DoTopRect(1,0);
DoRightRect(1,-1);
end
end;
 
 
 
begin
{Set matrix size}
SetLength(Mat,MatSize,MatSize);
{create matching rectangle}
R:=Rect(0,0,MatSize-1,MatSize-1);
Inx:=MatSize*MatSize;
{draw spiral around retangle and deflate rectanle until spiral is done}
while (R.Left<=R.Right) and (R.Top<=R.Bottom) do
begin
DoRect(R,Inx);
InflateRect(R,-1,-1);
end;
end;
 
 
 
procedure UlamPrimeSpiral(Image: TImage);
var Mat: TMatrix;
begin
MakeSqrSpiralMatrix(Mat,9);
DrawMatrixPrimes(Image,Mat);
end;
 
 
 
</syntaxhighlight>
{{out}}
<pre>
 
Elapsed Time: 1.550 ms.
 
</pre>
 
=={{header|EasyLang}}==
 
[https://easylang.dev/show/#cod=bZHdUsMgEIXveYqd8c5OmdTaC2eap0mIoglEIDX49LILi0w1F4HDfucsP9NmBtB+dXoBsy0gBQDoieZXeEKVPqfC5gx0KDMBfS5+velZJXntwX+6gL7iKSGLHYnuyvJdGgdS5qGHU21RqJOQwgAW9vS/dCLmYdxpcYyU/QBidXYAssh6igLlfBLclHxUUTOCsQVjC6Lr2JC/+t9MRr1qkb/RMp2LtuyDWnnLpl7BjrNkfcwykowsF3tTCYnlmPx+TaNBuyE9TCcv3CyoPXj9reAsqn02r3x9k3XwAcHC8ws6cFc4InEob42XiyOi74hi8VhbskUyo5E5lyqb7/xlqbFzAu75Bw== Run it]
 
<syntaxhighlight>
func isprim num .
if num < 2
return 0
.
i = 2
while i <= sqrt num
if num mod i = 0
return 0
.
i += 1
.
return 1
.
n = 1
x = 50
y = 50
dx = 1
dy = 0
#
proc turn . .
if dx = 1
dx = 0
dy = 1
elif dy = 1
dy = 0
dx = -1
elif dx = -1
dx = 0
dy = -1
else
dx = 1
dy = 0
.
.
proc step . .
n += 1
x += dx * 1
y += dy * 1
move x y
if isprim n = 1
circle 0.5
.
.
textsize 3
move x y
lng = 0
#
for k to 49
step
lng += 2
turn
for j to lng - 1
step
.
for i to 3
turn
for j to lng
step
.
.
.
</syntaxhighlight>
 
 
=={{header|EchoLisp}}==
The plot libray includes a '''plot-spiral''' function. The nice result is here : [http://www.echolalie.org/echolisp/help.html#plot-spiral EchoLisp Ulam spiral] .
<langsyntaxhighlight lang="scheme">
(lib 'plot)
 
Line 696 ⟶ 1,620:
(define (ulam n nmax) (if ( prime? n) *red* (gray (// n nmax))))
(plot-spiral ulam 1000) ;; range [0...1000]
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="elixir">defmodule Ulam do
defp cell(n, x, y, start) do
y = y - div(n, 2)
Line 733 ⟶ 1,657:
Ulam.show_spiral(9)
Ulam.show_spiral(25)
Ulam.show_spiral(25, ["#"," "])</langsyntaxhighlight>
 
{{out}}
Line 804 ⟶ 1,728:
 
=={{header|ERRE}}==
<langsyntaxhighlight ERRElang="erre">PROGRAM SPIRAL
 
!$INTEGER
Line 881 ⟶ 1,805:
!$DIM SPIRAL$[N,N]
GEN_ULAM(N,1)
END PROGRAM</langsyntaxhighlight>
{{out}}
<pre>
Line 904 ⟶ 1,828:
--- * --- --- --- * --- --- ---
* --- --- --- --- --- * --- ---
</pre>
 
=={{header|Factor}}==
{{trans|J}}
<syntaxhighlight lang="factor">USING: arrays grouping kernel math math.combinatorics
math.matrices math.primes math.ranges math.statistics
prettyprint sequences sequences.repeating ;
IN: rosetta-code.ulam-spiral
 
: counts ( n -- seq ) 1 [a,b] 2 repeat rest ;
 
: vals ( n -- seq )
[ -1 swap neg 2dup [ neg ] bi@ 4array ] [ 2 * 1 - cycle ] bi ;
 
: evJKT2 ( n -- seq )
[ counts ] [ vals ] bi [ <array> ] 2map concat ;
 
: spiral ( n -- matrix )
[ evJKT2 cum-sum inverse-permutation ] [ group ] bi ;
 
: ulam-spiral ( n -- matrix )
spiral dup dim first sq 1 -
[ swap - 1 + prime? "o " " " ? ] curry matrix-map ;
 
: ulam-demo ( -- ) 21 ulam-spiral simple-table. ;
 
MAIN: ulam-demo</syntaxhighlight>
{{out}}
<pre>
o o o o
o o o o
o o o o
o o o
o o o
o o o o
o o o
o o o o o o
o o o o o o o
o o o
o o o o o o o
o o o
o o
o o o o o o
o o o o o
o o
o o o o o
o o
o o o o
o o o o
o o o o
</pre>
 
=={{header|Forth}}==
{{works with|GNU Forth|0.7.0}}
All array manipulations were taken from Rosetta Code examples.
<syntaxhighlight lang="forth">
43 constant border \ grid size is border x border
border border * constant size
 
variable crawler \ position of the crawler
 
: set.crawler border 2 mod 0= if \ positions the crawler in the middle of the grid
size 2 / border 2/ + 1 - crawler !
else
size 2 / crawler ! then ;
set.crawler
create Grid size cells allot \ creates the grid
here constant GridEnd \ used for debugging
 
: is.divisor
over 2over
mod 0= swap drop + ;
 
: sub.one
swap 1 - swap ;
 
: next.div
is.divisor sub.one ;
: three.test \ counts divisors for numbers bigger than 2
dup 0
begin
next.div
over 1 = until
swap drop
swap drop 1 + ;
: not.prime \ counts the number of divisors. Primes have exactly two.
dup
2 < if drop true else
three.test then ;
 
: sub.four \ the crawler takes a number from the stack as direction
dup 4 > if 4 - then ; \ this word makes the number roll over.
\ 1-right 2-up 3-left 4-down
: craw.left \ rotates the crawler 90 degrees counter-clockwise
1 + sub.four ;
 
: scan.right
grid crawler @ 1 + cells + @ 0= ; \ checks if cell to the right of the crawler is zero
 
: scan.left
grid crawler @ 1 - cells + @ 0= ; \ cell to the left
 
: scan.up
grid crawler @ border - cells + @ 0= ; \ cell above
 
: scan.down
grid crawler @ border + cells + @ 0= ; \ and cell below
 
: crawler.go \ moves crawler one cell ahead checks cell to the left...
dup \ ...of the direction the crawler is facing, if zero, turns
1 = if crawler @ 1 + crawler ! scan.up if craw.left then else
dup
2 = if crawler @ border - crawler ! scan.left if craw.left then else
dup
3 = if crawler @ 1 - crawler ! scan.down if craw.left then else
dup
4 = if crawler @ border + crawler ! scan.right if craw.left then else
then then then then ;
: run.crawler \ crawler moves through the grid and fills it with numbers
border 2 < if 1 grid 0 cells + ! else \ if the grid is a single cell, puts 1 in it
crawler @ border - crawler ! \ crawler moves one step and turn before setting the first...
4 \ ...number so it is repositioned one cell up facing down
size -1 * 0 do i
i -1 * grid crawler @ cells + ! drop
crawler.go
-1 +loop then drop ;
: leave.primes \ removes non-primes from the grid
size 0 do i
grid i cells + @ not.prime if 0 grid i cells + ! then drop
loop ;
: star.draw1 \ draws a "*" where number is not zero
0> if 42 emit else 32 emit
then ;
: star.draw2
0> if 42 emit 32 emit else 32 emit 32 emit \ same but adds a space for better presentation
then ;
: star.draw3
0> if 32 emit 42 emit 32 emit else 32 emit 32 emit 32 emit \ adds two spaces
then ;
 
: draw.grid \ cuts the array into lines and displays it
page
size 0 do i
i border mod 0= if cr then
grid i cells + @ star.draw2 drop \ may use star.draw1 or 3 here
loop ;
: ulam.spiral run.crawler leave.primes draw.grid ; \ draws the spiral. Execute this word to run.
</syntaxhighlight>
{{out}}
<pre style="height:60ex;overflow:scroll">
 
 
* * * * * *
* * * * * *
* * * * * * *
* * * * * * *
* * * * *
* * * * * *
* * * *
* * * * * * *
* * * * * *
* * * * * * * * *
* * * * * * *
* * * * *
* * * * * * * * *
* * * * * * * * *
* * * * * *
* * * * * *
* * * * * * * * *
* * *
* * * * * * * * * * *
* * * * * * * * * * * *
* * * *
* * * * * * * * * * *
* * * * *
* *
* * * * * * * * * * * * *
* * * * * * * *
* * *
* * * * * * * * *
* * * * * * *
* * * * *
* * * * * * *
* * * * * * * * * *
* * * *
* * * * * * * *
* * * * * *
* * * * * *
* * * * * * *
* * * * *
* * * * * *
* * *
* * * * * *
* * * *
* * * * ok
 
</pre>
 
Line 909 ⟶ 2,039:
{{works with|Fortran|95 and later}}
Only works with odd sized squares
<langsyntaxhighlight lang="fortran">program ulam
implicit none
 
Line 984 ⟶ 2,114:
end if
end function
end program</langsyntaxhighlight>
Output:
<pre> O O O O O O O
Line 1,038 ⟶ 2,168:
===But if you can use complex numbers...===
Notice that there each move comes in pairs, lengths 1,1, 2,2, 3,3, 4,4, ... with a quarter turn for each move. The order of the work area must be an odd number so that there is a definite middle element to start with and the worm fits between the bounds of the work area rather than striking one wall and leaving tiles unused.
<syntaxhighlight lang="fortran">
<lang Fortran>
SUBROUTINE ULAMSPIRAL(START,ORDER) !Idle scribbles can lead to new ideas.
Careful with phasing: each lunge's first number is the second placed along its direction.
Line 1,044 ⟶ 2,174:
INTEGER ORDER !MUST be an odd number, so there is a middle.
INTEGER L,M,N !Counters.
INTEGER STEP,LUNGE !In some direction.
COMPLEX WAY,PLACE !Just so.
CHARACTER*1 SPLOT(0:1) !Tricks for output.
Line 1,096 ⟶ 2,227:
CALL ULAMSPIRAL(1,49)
END
</syntaxhighlight>
</lang>
One could escalate to declaring function IsPrime to be PURE so that it may be used in array expressions, such as CANVAS = SPLOT(ISPRIME(TILE)) where CANVAS is an array of single characters, but that would require another large array. TringTrying instead to do the conversion only a line at a time in the WRITE statement as SPLOT(ISPRIME(TILE(1:ORDER,L))) failed, only one symbol per line appeared. So instead, an older-style implicit DO-loop, and the results are...
<pre>
* * * * * * *
* * * * * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * *
* * * ** * * * * * * *
* * * * * * ** * * * * * * *
* * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * *
* * * * * * * * *
* * * * * * * *
* * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * *
* * * * * * * * *
* * * * * * * *
</pre>
Bounding the display with framework symbols might help readability, but is not in the specification.
 
=={{header|FreeBASIC}}==
This is actually better handled graphically.
 
<syntaxhighlight lang="freebasic">
#define SIZE 639
 
screenres SIZE, SIZE, 4
 
function is_prime( n as ulongint ) as boolean
if n < 2 then return false
if n = 2 then return true
if n mod 2 = 0 then return false
for i as uinteger = 3 to int(sqr(n))+1 step 2
if n mod i = 0 then return false
next i
return true
end function
 
function is_turn( byval n as unsigned integer ) as boolean
n -= 1
if int(sqr(n))^2 = n then return true
n = n - int(sqr(n))
if int(sqr(n))^2 = n then return true
return false
end function
 
dim as integer n = 1, x=SIZE/2, y=SIZE/2, dx = 1, dy = 0
 
do
if is_prime(n) then pset (x, y), 15
x = x + dx
y = y + dy
if x >= SIZE orelse y >= SIZE orelse x < 0 orelse y < 0 then exit do
n = n + 1
if is_turn(n) then
dx = -dx
swap dx, dy
end if
loop
 
sleep
end</syntaxhighlight>
 
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Ulam_spiral}}
 
'''Solution'''
 
[[File:Fōrmulæ - Ulam spiral 01.png]]
 
'''Test case'''
 
[[File:Fōrmulæ - Ulam spiral 02.png]]
 
[[File:Fōrmulæ - Ulam spiral 03.png]]
Bounding the display with framework symbols might help readability, but is not in the specification. For layout here, each line has had a space inserted at the start.
 
=={{header|Go}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="go">package main
 
import (
"math"
"fmt"
"regexp"
"strings"
)
 
Line 1,164 ⟶ 2,351:
 
const (
RIGHT Direction = 0iota
UP
UP Direction = 1
LEFT Direction = 2
DOWN Direction = 3
)
 
func generate(n,si int), [][]stringc byte) {
spirals := make([][]string, n)
for i := 0; i < n; i++ { spirals[i] = make([]string, n) }
dir := RIGHT
y := n / 2
var x int
if (n % 2 == 0) { x = y - 1 } else { x = y } // shift left for even n's
 
for j := si; j <= n * n - 1 + si; j++ {
if (isPrime(j)) { spiral[y][x] = fmt.Sprintf("%4d", j) } else { spiral[y][x] = " ---" }
if (c == 0) { s[y][x] = fmt.Sprintf("%3d", j) } else { s[y][x] = fmt.Sprintf("%2c ", c) }
} else { s[y][x] = "---" }
 
switch dir {
case RIGHT : if (x <= n - 1 && spirals[y - 1][x] == "" && j > si) { dir = UP }
case UP : if (spirals[y][x - 1] == "") { dir = LEFT }
case LEFT : if (x == 0 || spirals[y + 1][x] == "") { dir = DOWN }
case DOWN : if (spirals[y][x + 1] == "") { dir = RIGHT }
}
 
Line 1,196 ⟶ 2,385:
}
 
for _, row := range s { fmt.Println(fmt.Sprintf("%v", row)) }
return spiral
fmt.Println()
}
 
Line 1,208 ⟶ 2,398:
 
func main() {
u := generate(9, 1, 0) // with digits
generate(9, 1, '*') // with *
for _, row := range u { fmt.Println(fmt.Sprintf("%v", row)) }
}</syntaxhighlight>
fmt.Println()
 
r1 := regexp.MustCompile("\\[\\s+\\d+")
r2 := regexp.MustCompile("\\s+\\d+")
for _, row := range u {
s := fmt.Sprintf("%v", row)
fmt.Println(strings.Replace(r2.ReplaceAllString(r1.ReplaceAllString(s, "[ * "), " * "), ",", "", -1))
}
}</lang>
 
=={{header|Haskell}}==
 
<lang haskell>import Data.List
Haskell encourages splitting the task into indepentend parts each having very clear functionality:
 
1. preparation of data: a list of numbers is mapped into the list of symbols according to primality, or any other criterion.
 
2. spooling the list of arbitrary data into the spiral, forming a table.
3. displaying arbitrary table at a console or graphically.
 
As a program the given task then formulates as following:
 
<syntaxhighlight lang="haskell">import Data.List
import Data.Numbers.Primes
 
ulam n representation = swirl n . map representation </syntaxhighlight>
-- Add a row to existing spiral by rotating right and adding new row to top
-- Results in spirals that turn in the wrong direction and must later be fixed.
addRow :: [[Int]] -> [[Int]]
addRow spiral = let height = length spiral
width = length $ head spiral
row = [height*width+1.. height*width+height]
in row : reverse (transpose spiral)
 
Here we refference the function <code>swirl n</code>, which for a given (possibly infinite) list returns <code>n</code> whorls of a spiral.
-- Generate spiral by adding two rows (vertical & horizontal) to smaller spiral
preSpiral :: Int => [[Int]]
preSpiral 1 = [[1]]
preSpiral n = addRow $ addRow $ preSpiral (n-1)
 
The spiral is formed in a way we would fold a paper band: first we chop the band into pieces of increasing length, then we take necessary amount of pieces, finally we fold all pieces into the spiral, starting with the empty table by rotating it and adding pieces of data one by one:
-- Make ulamSpiral; fix spiral direction by flipping preSpiral.
ulamSpiral :: Int => [[Int]]
ulamSpiral n | odd n = reverse $ preSpiral n
| otherwise = map reverse $ preSpiral n
 
<syntaxhighlight lang="haskell">swirl n = spool . take (2*(n-1)+1) . chop 1
-- Make and print ulamSpiral:
-- Use converter to change numbers to strings.
-- Change empty strings to dashes.
-- Pad strings out to correct length before printing.
prettyPrintSpiral :: Int -> (Int -> String) -> IO ()
prettyPrintSpiral n converter =
let stringSpiral = map (map converter) (ulamSpiral n)
maxLen = maximum (map (maximum.map length) stringSpiral)
dashFunc s = if s == "" then replicate maxLen '-' else s
padFunc s = replicate (maxLen - length s) ' ' ++ s
padded = map (padFunc.dashFunc)
showRow = unwords.padded
in mapM_ (putStrLn.showRow) stringSpiral
 
chop n lst = let (x,(y,z)) = splitAt n <$> splitAt n lst
in x:y:chop (n+1) z
 
spool = foldl (\table piece -> piece : rotate table) [[]]
main :: IO ()
where rotate = reverse . transpose</syntaxhighlight>
main = do
-- Display with converter that shows primes as Strings.
prettyPrintSpiral 10 (\n -> if isPrime n then show n else "")
 
That's it!
putStrLn ""
 
=== Textual output ===
-- Display with converter that shows primes as single dots.
 
prettyPrintSpiral 60 (\n -> if isPrime n then "*" else " ") </lang>
Pretty printing the table of strings with given column width is simple:
{{out}}
 
<pre style="font-size:80%">-- -- -- 97 -- -- -- -- -- --
<syntaxhighlight lang="haskell">showTable w = foldMap (putStrLn . foldMap pad)
-- -- -- -- 61 -- 59 -- -- --
where pad s = take w $ s ++ repeat ' '</syntaxhighlight>
-- 37 -- -- -- -- -- 31 -- 89
 
67 -- 17 -- -- -- 13 -- -- --
{{Out}}
-- -- -- 5 -- 3 -- 29 -- --
 
-- -- 19 -- -- 2 11 -- 53 --
<pre>λ> showTable 3 $ ulam 10 show [1..]
-- 41 -- 7 -- -- -- -- -- --
7191 --92 --93 --94 2395 --96 --97 --98 --99 --100
--90 4357 --58 --59 --60 4761 --62 --63 --64 65 83
7389 --56 --31 --32 --33 --34 7935 --36 --37 66 --
88 55 30 13 14 15 16 17 38 67
87 54 29 12 3 4 5 18 39 68
86 53 28 11 2 1 6 19 40 69
85 52 27 10 9 8 7 20 41 70
84 51 26 25 24 23 22 21 42 71
83 50 49 48 47 46 45 44 43 72
82 81 80 79 78 77 76 75 74 73
 
λ> showTable 3 $ ulam 10 (\x -> if isPrime x then show x else " . ") [1..]
. . . . . . 97 . . .
. . . 59 . 61 . . . .
89 . 31 . . . . . 37 .
. . . 13 . . . 17 . 67
. . 29 . 3 . 5 . . .
. 53 . 11 2 . . 19 . .
. . . . . . 7 . 41 .
. . . . . 23 . . . 71
83 . . . 47 . . . 43 .
. . . 79 . . . . . 73
 
λ> showTable 2 $ ulam 20 (\x -> if isPrime x then "*" else "") [1..]
* * *
* * * *
* * * *
* * *
* * *
* * * *
* * *
* * * * * *
* * * * * *
* * *
* * * * * * *
* * *
* *
* * * * * *
* * * * *
* *
* * * * *
* *
* * *
* * * * </pre>
 
The high modularity of the program allows us easily to start from any number and to proceed with any step size:
 
<pre>λ> showTable 2 $ ulam 20 (\x -> if isPrime x then "*" else "") [3,5..]
* * * *
* * * * * * *
* * * * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * *
* * * *
* * * * * * * * * *
* * * * * * * * * * *
* * * *
* * * * * * * * * * *
* * * * * *
* * * * * *
* * * * * * * * * * * *
* * * *
* * * * * *
* * * * * * *
* * * * </pre>
 
Or we can form a spiral out of arbitrary data: &nbsp; (''but that doesn't show the primes as this task requires''):
 
<pre>λ> showTable 1 $ ulam 10 (:[]) "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse consequat lectus at massa tristique, ut vulputate arcu pretium."
assa trist
m Suspendi
.nsectets
ttodolorus
aic rem re
l moL s
se,uspiiac
u tema tdo
tgnicsipin
cel tauqes</pre>
 
=== Graphical output ===
 
Simple graphical output could be done using <code>Diagrams</code> framework:
<syntaxhighlight lang="haskell">import Diagrams.Prelude
import Diagrams.Backend.SVG.CmdLine
 
drawTable tbl = foldl1 (===) $ map (foldl1 (|||)) tbl :: Diagram B
 
dots x = (circle 1 # if isPrime x then fc black else fc white) :: Diagram B
 
main = mainWith $ drawTable $ ulam 100 dots [1..]</syntaxhighlight>
* * * * * * * *
* * * * * * * * * *
* * * * * * *
* * * * * *
* * * * * * * * * * *
* * * * *
* * * * * * * *
* * * * * * * * * *
* * * * * *
* * * * * * * * * * *
* * * * * * * * *
* * * * * * *
* * * * * * * * * * * *
* * * * * *
* * * * * * *
* * * * * * *
* * * * * * * *
* * * * * *
* * * * * * * * * *
* * * * * * * * *
* * * * * * *
* * * * * * * * * *
* * * * * * * * * * * *
* * * * * * *
* * * * * * * * * *
* * * * * * * * * * * * *
* * * *
* * * * * * * * * * * * *
* * * * * * * * * * * * * * *
* * * * *
* * * * * * * * * * * * * *
* * * * * *
* * *
* * * * * * * * * * * * * * * *
* * * * * * * * * * * *
* * * *
* * * * * * * * * *
* * * * * * * *
* * * * *
* * * * * * * * * *
* * * * * * * * * * * * * *
* * * *
* * * * * * * * * * * *
* * * * * * * * * *
* * * * * * *
* * * * * * * *
* * * * * * *
* * * * * * * *
* * * * * *
* * * * * * * * * *
* * * * * * *
* * * * * * *
* * * * * * * * * *
* * * *
* * * * * * * *
* * * * * * *
* * * * * * * *
* * * * * * *
* * * * *
* * * * * * * </pre>
 
=={{header|J}}==
Line 1,343 ⟶ 2,542:
Let's start with our implementation of [[Spiral_matrix#J|spiral]]:
 
<langsyntaxhighlight Jlang="j">spiral =: ,~ $ [: /: }.@(2 # >:@i.@-) +/\@# <:@+: $ (, -)@(1&,)</langsyntaxhighlight>
 
We can get a spiral starting with 1 in the center of the square by subtracting these values from the square of our size argument:
 
<langsyntaxhighlight Jlang="j"> spiral 5
0 1 2 3 4
15 16 17 18 5
Line 1,358 ⟶ 2,557:
11 2 1 6 19
12 3 4 5 18
13 14 15 16 17</langsyntaxhighlight>
 
Next, we want to determine which of these numbers are prime:
 
<langsyntaxhighlight Jlang="j"> (1 p: *: - spiral) 5
0 0 1 0 0
0 0 0 1 0
1 1 0 0 1
0 1 0 1 0
1 0 0 0 1</langsyntaxhighlight>
 
And, finally, we want to use these values to select from a pair of characters:
 
<langsyntaxhighlight Jlang="j"> (' o' {~ 1 p: *: - spiral) 5
o
o
oo o
o o
o o</langsyntaxhighlight>
 
If we want our spiral to start with some value other than 1, we'd add that value - 1 to our numbers right before the prime check. For this, we want a function which returns 0 when there's no left argument and one less than the left argument when it that value present. We can use : for this -- it takes two verbs, the left of which is used when no left argument is present and the right one is used when a left argument is present. (And note that in J, : is a token forming character, so we will need to leave a space to the left of : so that it does not form a different token):
 
<langsyntaxhighlight Jlang="j"> (0: :(<:@[)) ''
0
3 (0: :(<:@[)) ''
2</langsyntaxhighlight>
 
We also want to specify that our initial computations only respect the right argument, and we should maybe add a space after every character to get more of a square aspect ratio in typical text displays:
 
<langsyntaxhighlight Jlang="j">ulam=: 1j1 #"1 ' o' {~ 1 p: 0: :(<:@[) + *:@] - spiral@]</langsyntaxhighlight>
 
And here it is in action:
 
<langsyntaxhighlight Jlang="j"> ulam 16
o o
o o o
Line 1,419 ⟶ 2,618:
o o o o
o
o o o </langsyntaxhighlight>
 
To transform these spirals to the orientation which has recently been added as a part of the task, you could flip them horizontally (|."1) and vertically (|.)
Line 1,429 ⟶ 2,628:
=={{header|Java}}==
{{works with|Java|1.5+}}
<langsyntaxhighlight lang="java5">import java.util.Arrays;
 
public class Ulam{
Line 1,492 ⟶ 2,691:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>[ --- --- --- --- 61 --- 59 --- ---]
Line 1,513 ⟶ 2,712:
[ --- * --- --- --- * --- --- ---]
[ * --- --- --- --- --- * --- ---]</pre>
 
=== Large scale Ulam Spiral ===
[[File:ulam_large_java.gif|300px|thumb|right]]
{{works with|Java|8}}
<syntaxhighlight lang="java">import java.awt.*;
import javax.swing.*;
 
public class LargeUlamSpiral extends JPanel {
 
public LargeUlamSpiral() {
setPreferredSize(new Dimension(605, 605));
setBackground(Color.white);
}
 
private boolean isPrime(int n) {
if (n <= 2 || n % 2 == 0)
return n == 2;
for (int i = 3; i * i <= n; i += 2)
if (n % i == 0)
return false;
return true;
}
 
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
 
g.setColor(getForeground());
 
double angle = 0.0;
int x = 300, y = 300, dx = 1, dy = 0;
 
for (int i = 1, step = 1, turn = 1; i < 40_000; i++) {
 
if (isPrime(i))
g.fillRect(x, y, 2, 2);
 
x += dx * 3;
y += dy * 3;
 
if (i == turn) {
 
angle += 90.0;
 
if ((dx == 0 && dy == -1) || (dx == 0 && dy == 1))
step++;
 
turn += step;
 
dx = (int) Math.cos(Math.toRadians(angle));
dy = (int) Math.sin(Math.toRadians(-angle));
}
}
}
 
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Large Ulam Spiral");
f.setResizable(false);
f.add(new LargeUlamSpiral(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}</syntaxhighlight>
 
=== Small scale Ulam Spiral ===
[[File:ulam_spiral_java.gif|300px|thumb|right]]
{{works with|Java|8}}
<syntaxhighlight lang="java">import java.awt.*;
import javax.swing.*;
 
public class UlamSpiral extends JPanel {
 
Font primeFont = new Font("Arial", Font.BOLD, 20);
Font compositeFont = new Font("Arial", Font.PLAIN, 16);
 
public UlamSpiral() {
setPreferredSize(new Dimension(640, 640));
setBackground(Color.white);
}
 
private boolean isPrime(int n) {
if (n <= 2 || n % 2 == 0)
return n == 2;
for (int i = 3; i * i <= n; i += 2)
if (n % i == 0)
return false;
return true;
}
 
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
 
g.setStroke(new BasicStroke(2));
 
double angle = 0.0;
int x = 280, y = 330, dx = 1, dy = 0;
 
g.setColor(getForeground());
g.drawLine(x, y - 5, x + 50, y - 5);
 
for (int i = 1, step = 1, turn = 1; i < 100; i++) {
 
g.setColor(getBackground());
g.fillRect(x - 5, y - 20, 30, 30);
g.setColor(getForeground());
g.setFont(isPrime(i) ? primeFont : compositeFont);
g.drawString(String.valueOf(i), x + (i < 10 ? 4 : 0), y);
 
x += dx * 50;
y += dy * 50;
 
if (i == turn) {
angle += 90.0;
 
if ((dx == 0 && dy == -1) || (dx == 0 && dy == 1))
step++;
 
turn += step;
 
dx = (int) Math.cos(Math.toRadians(angle));
dy = (int) Math.sin(Math.toRadians(-angle));
 
g.translate(9, -5);
g.drawLine(x, y, x + dx * step * 50, y + dy * step * 50);
g.translate(-9, 5);
}
}
}
 
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Ulam Spiral");
f.setResizable(false);
f.add(new UlamSpiral(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}</syntaxhighlight>
 
=={{header|JavaScript}}==
You can find plotting helper functions here on RosettaCode Wiki: [[User:AnatolV/Helper_Functions| VOE.js]] v.2.0.<br>
'''Note:'''
* Find "printed" spirals in console (Chrome).<br>
* An image uploading is still blocked. But you have a browser!? So, copy/paste/save this page and double click it.
 
{{trans|PARI/GP}}
{{Works with|Chrome}} (or any other browser supporting Canvas tag)
<syntaxhighlight lang="html">
<!-- UlamSpiral.html -->
<html>
<head><title>Ulam Spiral</title>
<script src="VOE.js"></script>
<script>
// http://rosettacode.org/wiki/User:AnatolV/Helper_Functions
// Use v.2.0
var pst;
 
// ***** Additional helper functions
// Pad number from left
function padLeft(n,ns) {
return (" " + n).slice(-ns);
}
 
// Is number n a prime?
function isPrime(n) {
var n2=Math.sqrt(n);
for(var i=2; i<=n2; i++) {
if(n%i === 0) return false;
}//fend i
return n !== 1;
}
 
function insm(mat,x,y) {
var xz=mat[0].length, yz=xz;
return(x>=0 && x<xz && y>=0 && y<yz)
}
// *****
 
function rbCheck() {
if (document.getElementById('rbDef').checked) {pst=0}
if (document.getElementById('rbAst').checked) {pst=1}
if (document.getElementById('rbNum').checked) {pst=2}
}
function rbSet() {
document.getElementById("rbDef").checked = true;
rbCheck();
}
 
// The Ulam Spiral
function pspUlam() {
var i, j, x, y, xmx, ymx, cnt, dir, M, Mij, sp=" ", sc=3;
// Setting basic vars for canvas and matrix
var cvs = document.getElementById('cvsId');
var ctx = cvs.getContext("2d");
if(pst<0||pst>2) {pst=0}
if(pst==0) {n=100; sc=3} else {n=10; sc=5}
console.log("sc", typeof(sc));
if(n%2==0) {n++};
var n2=n*n, pch, sz=n2.toString().length, pch2=sp.repeat(sz);
var fgc="navy", bgc="white";
// Create matrix, finding number of rows and columns
var M=new Array(n);
for (i=0; i<n; i++) { M[i]=new Array(n);
for (j=0; j<n; j++) {M[i][j]=0} }
var r = M[0].length, c = M.length, k=0, dsz=1;
// Logging init parameters
var ttl="Matrix ("+r+","+c+")";
console.log(" *** Ulam spiral: ",n,"x",n,"p-flag=",pst, "sc", sc);
// Generating and plotting Ulam spiral
x=y=Math.floor(n/2)+1; xmx=ymx=cnt=1; dir="R";
for(var i=1; i<=n2; i++) { //
if(isPrime(i)) // if prime
{ if(!insm(M,x,y)) {break};
if(pst==2) {M[y][x]=i} else {M[y][x]=1};
}
// all numbers
if(dir=="R") {if(xmx>0){x++;xmx--} else {dir="U";ymx=cnt;y--;ymx--} continue};
if(dir=="U") {if(ymx>0){y--;ymx--} else {dir="L";cnt++;xmx=cnt;x--;xmx--} continue};
if(dir=="L") {if(xmx>0){x--;xmx--} else {dir="D";ymx=cnt;y++;ymx--} continue};
if(dir=="D") {if(ymx>0){y++;ymx--} else {dir="R";cnt++;xmx=cnt;x++;xmx--}; continue};
}//fend i
//Plot/Print according to the p-flag(0-real plot,1-"*",2-primes)
if(pst==0) {pmat01(M, fgc, bgc, sc, 0); return};
var logs;
if(pst==1) {for(i=1;i<n;i++) {logs="|";
for(j=1;j<n;j++) { Mij=M[i][j]; if(Mij>0) {pch="*"} else {pch=" "};
logs+=" "+pch;}
logs+="|"; console.log(logs);}//fiend
pmat01(M, fgc, bgc, sc, 0); console.log("sc", sc);
return;
}//ifend
//console.log(" ",pch);} console.log(" ")}; return};
if(pst==2) {for(i=1;i<n;i++) {logs="|";
for(j=1;j<n;j++) {Mij=M[i][j];
if(Mij==0) {pch=pch2}
else {pch=padLeft(Mij,sz)};
logs+=pch; } //" "+
logs+=" |"; console.log(logs);}//fiend
pmat01(M, fgc, bgc, sc, 0); console.log("sc", sc);
return;
}//ifend
 
}//func end
// ******************************************
</script></head>
<body onload='rbSet();' style="font-family: arial, helvatica, sans-serif;">
<b>Plot/print style:</b>
<input type="radio" onclick="rbCheck();" name="rb" id="rbDef"/><b>Plot</b>&nbsp;
<input type="radio" onclick="rbCheck();" name="rb" id="rbAst"/><b>Print *</b>&nbsp;
<input type="radio" onclick="rbCheck();" name="rb" id="rbNum"/><b>Print numbers</b>&nbsp;
<input type="button" value="Plot it!" onclick="pspUlam();">
<h3>Ulam Spiral</h3>
<canvas id="cvsId" width="300" height="300" style="border: 2px inset;"></canvas>
</body>
</html>
</syntaxhighlight>
{{Output}}
 
<pre>
Print using "*"
===============
Plot, plus this:
*** Ulam spiral: 11 x 11 p-flag= 1 sc 5
| |
| * * |
| * * |
| * * * |
| * * * |
| * * * *|
| * * |
| * * |
| * * |
| * * |
 
matrix 'signature': Matrix(11x11) 22 dots
Print prime numbers
===================
Plot, plus this:
*** Ulam spiral: 11 x 11 p-flag= 2 sc 5
| |
| 61 59 |
| 37 31 |
| 67 17 13 |
| 5 3 29 |
| 19 2 11 53 |
| 41 7 |
| 71 23 |
| 43 47 |
| 73 79 |
plot:
=====
Plot, plus this:
*** Ulam spiral: 101 x 101 p-flag= 0 sc 3
matrix 'signature': Matrix(101x101) 1208 dots
</pre>
 
=={{header|jq}}==
{{trans|Wren}}
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
 
See [[Erdős-primes#jq]] for a suitable definition of `is_prime` as used here.
<syntaxhighlight lang="jq">def array($init): [range(0; .) | $init];
 
# Test if input is a one-character string holding a digit
def isDigit:
type=="string" and length==1 and explode[0] as $c | (48 <= $c and $c <= 57);
 
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
 
def generate($n; $i; $c):
if $n <= 1 then "'n' must be more than 1." | error
else { s: ($n|array(array(""))),
dir: "right",
y: (($n/2)|floor) }
| .x = if ($n % 2 == 0) then .y - 1 else .y end # shift left for even n
| reduce range($i; $n * $n + $i) as $j (.;
.s[.y][.x] = (
if $j | is_prime
then (if $c|isDigit then $j|lpad(4) else " \($c) " end)
else " ---"
end)
| if .dir == "right"
then if (.x <= $n - 1 and .s[.y - 1][.x] == "" and $j > i) then .dir = "up" else . end
elif .dir == "up"
then if (.s[.y][.x - 1] == "") then .dir = "left" else . end
elif .dir == "left"
then if (.x == 0 or .s[.y + 1][.x] == "") then .dir = "down" else . end
elif .dir == "down"
then if (.s[.y][.x + 1] == "") then .dir = "right" else . end
else .
end
| if .dir == "right" then .x += 1
elif .dir == "up" then .y += -1
elif .dir == "left" then .x += -1
elif .dir == "down" then .y += 1
else .
end )
| .s[] | join(" ")
end ;
 
# with digits
generate(9; 1; "0"), "",
 
# with *
generate(9; 1; "*")
</syntaxhighlight>
{{out}}
As for [[#Wren|Wren]].
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
 
<syntaxhighlight lang="julia">using Primes
 
function ulamspiral(ord::Int)
# Possible directions
dirs = [[0, 1], [-1, 0], [0, -1], [1, 0]]
# fdir = ["→", "↑", "←", "↓"] # for debug pourpose
cur = maxsteps = 1 # starting direction & starting max steps
steps = n = 0 # starting steps & starting number in cell
pos = [ord ÷ 2 + 1, isodd(ord) ? ord ÷ 2 + 1 : ord ÷ 2] # starting position
M = Matrix{Bool}(ord, ord) # result matrix
while n < ord ^ 2 # main loop (stop when the matrix is filled)
n += 1
M[pos[1], pos[2]] = isprime(n)
steps += 1
# Debug print
# @printf("M[%i, %i] = %5s (%2i), step %i/%i, nxt %s\n", pos[1], pos[2], isprime(n), n, steps, maxsteps, fdir[cur])
pos .+= dirs[cur] # increment position
if steps == maxsteps # if reached max number of steps in that direction...
steps = 0 # ...reset steps
if iseven(cur) maxsteps += 1 end # if the current direction is even increase the number of steps
cur += 1 # change direction
if cur > 4 cur -= 4 end # correct overflow
end
end
return M
end
 
mprint(m::Matrix) = for i in 1:size(m, 1) println(join(el ? " ∙ " : " " for el in m[i, :]), '\n') end
 
M = ulamspiral(9)
mprint(M)</syntaxhighlight>
 
{{out}}
<pre> ∙ ∙
 
∙ ∙
 
∙ ∙ ∙
 
∙ ∙ ∙
 
∙ ∙ ∙ ∙
 
∙ ∙
 
∙ ∙
 
∙ ∙
 
∙ ∙ </pre>
 
=={{header|Kotlin}}==
{{trans|Java}}
<syntaxhighlight lang="scala">object Ulam {
<lang scala>import kotlin.text.Regex
fun generate(n: Int, i: Int = 1, c: Char = '*') {
 
object Ulam {
fun generate(n: Int, s: Int = 1): Array<Array<String>> {
require(n > 1)
val spirals = Array(n) { Array(n, { "" }) }
var dir = Direction.RIGHT
var y = n / 2
var x = if (n % 2 == 0) y - 1 else y // shift left for even n's
for (j in si..n * n - 1 + si) {
spirals[y][x] = if (isPrime(j)) if (c.isDigit()) "%4d".format(j) else " $c " else " ---"
 
when (dir) {
Direction.RIGHT -> if (x <= n - 1 && spirals[y - 1][x].none() && j > si) dir = Direction.UP
Direction.UP -> if (spirals[y][x - 1].none()) dir = Direction.LEFT
Direction.LEFT -> if (x == 0 || spirals[y + 1][x].none()) dir = Direction.DOWN
Direction.DOWN -> if (spirals[y][x + 1].none()) dir = Direction.RIGHT
}
 
Line 1,542 ⟶ 3,160:
}
}
for (row in s) println("[" + row.joinToString("") + ']')
return spiral
println()
}
 
Line 1,562 ⟶ 3,181:
 
fun main(args: Array<String>) {
val u = Ulam.generate(9, c = '0')
Ulam.generate(9)
for (row in u) println(row.toList().toString().replace(",", ""))
}</syntaxhighlight>
println()
val c = '*'
val r1 = Regex("\\[\\s+\\d+")
val r2 = Regex("\\s+\\d+")
for (row in u)
println(row.toList().toString().replace(r1, "[ $c ").replace(r2, " $c ").replace(",", ""))
}</lang>
 
=={{header|PerlLua}}==
<syntaxhighlight lang="lua">local function ulamspiral(n, f)
{{trans|python}}
print("n = " .. n)
<lang perl>use ntheory qw/is_prime/;
local function isprime(p)
use Imager;
if p < 2 then return false end
if p % 2 == 0 then return p==2 end
if p % 3 == 0 then return p==3 end
local limit = math.sqrt(p)
for f = 5, limit, 6 do
if p % f == 0 or p % (f+2) == 0 then return false end
end
return true
end
local function spiral(x, y)
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(isprime(spiral(x,y))))
end
print()
end
print()
end
 
-- filling a 132 column terminal (with a 2-wide glyph to better preserve aspect ratio)
my $n = shift || 512;
ulamspiral(132/2, function(b) return b and "██" or " " end)</syntaxhighlight>
my $start = shift || 1;
{{out}}
my $file = "ulam.png";
<pre>n = 66.0
 
██ ██ ██ ██ ██
sub cell {
██ ██ ██ ██ ██ ██ ██
my($n, $x, $y, $start) = @_;
██ ██ ██ ██ ██ ██ ██
$y -= $n>>1;
██ ██ ██ ██ ██ ██ ██ ██ ██
$x -= ($n-1)>>1;
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
my $l = 2*(abs($x) > abs($y) ? abs($x) : abs($y));
██ ██ ██ ██ ██ ██ ██
my $d = ($y > $x) ? $l*3 + $x + $y : $l-$x-$y;
██ ██ ██ ██ ██ ██ ██
($l-1)**2 + $d + $start - 1;
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ████ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██
██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██
</pre>
=={{header|M2000 Interpreter}}==
{{trans|VBScript}}
<syntaxhighlight lang="m2000 interpreter">
Module Ulam_Spiral {
build_spiral(9)
Sub build_spiral(n)
if n mod 2=0 then n++
Local matrix(n,n) as string
Local x = (n-1)/2, y = (n-1)/2
Local x_max = 1, y_max = 1, count = 1
Local dir = "R", i, l=Len(n*n+"")
For i = 1 To n*n
If @IsPrime(i) Then
matrix(x,y) = Right$("000"+i,l)
Else
matrix(x,y) = String$("-", l) // this is different from VbScript
End If
Select Case dir
Case "R"
{
If x_max > 0 Then
x++:x_max--
Else
dir = "U" : y_max = count
y--:y_max--
End If
}
Case "U"
{
If y_max > 0 Then
y-- :y_max--
Else
dir = "L" : count++: x_max = count
x--:x_max--
End If
}
Case "L"
{
If x_max > 0 Then
x--:x_max--
Else
dir = "D" : y_max = count
y++:y_max--
End If
}
Case "D"
{
If y_max > 0 Then
y++:y_max--
Else
dir = "R" : count++: x_max = count
x++:x_max--
End If
}
End Select
Next
For y = 0 To n - 1
For x = 0 To n - 1
If x = n - 1 Then
Print matrix(x,y)
Else
print matrix(x,y)+" ";
End If
Next
print
Next
End Sub
Function IsPrime(n)
If n = 2 Then
= True
Else.If n <= 1 Or n Mod 2 = 0 Then
= False
Else
= True
if 3>Int(Sqrt(n)) then exit function
// for/next in M2000 always executed (from step used the absolute value)
local i
For i = 3 To Int(Sqrt(n)) Step 2
If n Mod i = 0 Then
= False
Exit For
End If
Next
End If
End Function
}
Ulam_Spiral
</syntaxhighlight>
{{out}}
same as VBScript
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
my $black = Imager::Color->new('#000000');
<syntaxhighlight lang="mathematica">ClearAll[iCCWSpiralEast]
my $white = Imager::Color->new('#FFFFFF');
iCCWSpiralEast[n_Integer]:=Table[(1/2 (-1)^# ({1,-1} (Abs[#^2-t]-#)+#^2-t-Mod[#,2])&)[Round[Sqrt[t]]],{t,0,n-1}]
my $img = Imager->new(xsize => $n, ysize => $n, channels => 1);
n=20
$img->box(filled=>1, color=>$white);
start=1;
pts=iCCWSpiralEast[n^2];
pts=Pick[pts,PrimeQ[start+Range[n^2]-1],True];
grid=Table[({i,j}/.(Alternatives@@pts)->"#")/.{_,_}->" ",{j,Round[n/2],-Round[n/2],-1},{i,-Round[n/2],Round[n/2],1}];
Grid[grid]</syntaxhighlight>
{{out}}
<pre> * * *
* * * *
* * * *
* * *
* * *
* * * *
* * *
* * * * * *
* * * * * *
* * *
* * ** * * *
* * *
* *
* * * * * *
* * * * *
* *
* * * * *
* *
* * *
* * * * </pre>
 
=={{header|Maxima}}==
for my $y (0 .. $n-1) {
[[File:Ulam spiral.png|thumb|Ulam spiral powered by Maxima]]
for my $x (0 .. $n-1) {
Using the function defined in the Spiral matrix task
my $v = cell($n, $x, $y, $start);
<syntaxhighlight lang="maxima">
$img->setpixel(x => $x, y => $y, color => $black) if is_prime($v);
/* Adapting the spiral to the problem requirements */
}
spiral_from_center(n):=(n^2+1)*matrixmap(lambda([x],x+1),zeromatrix(n,n))-spiral(n)$
}
 
/* Testing */
spiral_from_center(35)$
matrixmap(lambda([x],if primep(x) then "O" else ""),%);
</syntaxhighlight>
 
=={{header|Nim}}==
 
===Displaying in terminal===
<syntaxhighlight lang="nim">import strutils
 
const N = 51 # Grid width and height.
 
type
Vec2 = tuple[x, y: int]
Grid = array[N, array[N, string]]
 
const Deltas: array[4, Vec2] = [(0, 1), (-1, 0), (0, -1), (1, 0)]
 
 
proc `+`(v1, v2: Vec2): Vec2 =
## Vector addition.
(v1.x + v2.x, v1.y + v2.y)
 
 
proc isPrime(n: Positive): bool =
## Check if a number is prime.
if n == 1: return false
if (n and 1) == 0: return n == 2
if (n mod 3) == 0: return n == 3
var delta = 2
var d = 5
while d * d <= n:
if n mod d == 0: return false
inc d, delta
delta = 6 - delta
return true
 
 
proc fill(grid: var Grid; start: Positive = 1) =
## Fill the grid using Ulam algorithm.
 
template isEmpty(pos: Vec2): bool = grid[pos.x][pos.y].len == 0
 
# Fill the grid with successive numbers (as strings).
var pos: Vec2 = (N div 2, N div 2)
grid[pos.x][pos.y] = $start
var currIdx = 3
for n in (start + 1)..<(start + N * N):
let nextIdx = (currIdx + 1) and 3
var nextPos = pos + Deltas[nextIdx]
if nextPos.isEmpty():
# Direction change is OK.
currIdx = nextIdx
else:
# Continue in same direction.
nextPos = pos + Deltas[currIdx]
pos = move(nextPos)
grid[pos.x][pos.y] = $n
 
# Replace the values with a symbol (if prime) or a space (if composite).
for row in 0..<N:
for col in 0..<N:
grid[row][col] = if grid[row][col].parseInt().isPrime(): "• " else: " "
 
 
var grid: Grid
grid.fill()
for row in grid:
echo row.join()</syntaxhighlight>
 
$img->write(file => $file) or die "Cannot write $file: ", $img->errstr, "\n";</lang>
{{out}}
<pre> • • • •
Creates an image file <tt>ulam.png</tt> in current directory similar to the one on MathWorld. The square dimension can be optionally specified.
• • • • • • •
• • • • • • • •
• • • • •
• • • • • • • •
• • • • • • •
• • • • • • •
• • • • • • • • • •
• • • • •
• • • • • •
• • • • • •
• • • • • • •
• • • • • •
• • • • • • • • •
• • • • • • • • •
• • • • • • •
• • • • • • • • • •
• • • • • • • • • • •
• • • • • •
• • • • • • • •
• • • • • • • • • • •
• • • •
• • • • • • • • • • • •
• • • • • • • • • • • • •
• • • •
• • • • • • • • • • • •
• • • • • •
• •
• • • • • • • • • • • • • • •
• • • • • • • • • •
• • • •
• • • • • • • • •
• • • • • • •
• • • • •
• • • • • • • • •
• • • • • • • • • • • •
• • • •
• • • • • • • • • •
• • • • • • • •
• • • • • • •
• • • • • • • •
• • • • •
• • • • • • •
• • • •
• • • • • • •
• • • • • •
• • • • • •
• • • • • • • •
• • • •
• • • • • • • •
• • • • • </pre>
 
===Writing a PNG image===
{{libheader|imageman}}
Writing in a file, it is possible to create much bigger images.
 
<syntaxhighlight lang="nim">import imageman
 
const
N = 501 # Grid width and height.
FG = ColorRGBU [byte 255, 255, 255]
BG = ColorRGBU [byte 0, 0, 0]
 
type
Vec2 = tuple[x, y: int]
Grid = array[N, array[N, int32]]
 
const Deltas: array[4, Vec2] = [(0, 1), (-1, 0), (0, -1), (1, 0)]
 
 
proc `+`(v1, v2: Vec2): Vec2 =
## Vector addition.
(v1.x + v2.x, v1.y + v2.y)
 
 
proc isPrime(n: Positive): bool =
## Check if a number is prime.
if n == 1: return false
if (n and 1) == 0: return n == 2
if (n mod 3) == 0: return n == 3
var delta = 2
var d = 5
while d * d <= n:
if n mod d == 0: return false
inc d, delta
delta = 6 - delta
return true
 
 
proc fill(grid: var Grid; start: Positive = 1) =
## Fill the grid using Ulam algorithm.
 
template isEmpty(pos: Vec2): bool = grid[pos.x][pos.y] == 0
 
let start = start.int32
 
# Fill the grid with successive numbers (as strings).
var pos: Vec2 = (N div 2, N div 2)
grid[pos.x][pos.y] = start
var currIdx = 3
for n in (start + 1)..<(start + N * N):
let nextIdx = (currIdx + 1) and 3
var nextPos = pos + Deltas[nextIdx]
if nextPos.isEmpty():
# Direction change is OK.
currIdx = nextIdx
else:
# Continue in same direction.
nextPos = pos + Deltas[currIdx]
pos = move(nextPos)
grid[pos.x][pos.y] = n
 
proc apply(img: var Image; grid: Grid) =
## Fill the image with foreground pixel (for primes) or nothing (for composites).
for row in 0..<N:
for col in 0..<N:
if grid[row][col].isPrime():
img[row, col] = FG
 
 
var grid: Grid
grid.fill()
 
var image = initImage[ColorRGBU](N, N)
image.fill(BG)
image.apply(grid)
image.savePNG("ulam_spiral.png", compression = 9)</syntaxhighlight>
 
=={{header|PARI/GP}}==
In this version function plotulamspir() was translated from VB, plus upgraded to plot/print different kind of Ulam spirals.
My own plotting helper functions and string functions were used and made it possible.
You can find all of them here on RosettaCode Wiki.
 
[[File:ULAMspiral1.png|200px|right|thumb|Output ULAMspiral1.png]]
[[File:ULAMspiral2.png|200px|right|thumb|Output ULAMspiral2.png]]
 
{{Works with|PARI/GP|2.7.4 and above}}
 
<syntaxhighlight lang="parigp">
\\ Ulam spiral (plotting/printing)
\\ 4/19/16 aev
plotulamspir(n,pflg=0)={
my(n=if(n%2==0,n++,n),M=matrix(n,n),x,y,xmx,ymx,cnt,dir,n2=n*n,pch,sz=#Str(n2),pch2=srepeat(" ",sz));
if(pflg<0||pflg>2,pflg=0);
print(" *** Ulam spiral: ",n,"x",n," matrix, p-flag=",pflg);
x=y=n\2+1; xmx=ymx=cnt=1; dir="R";
for(i=1,n2,
if(isprime(i), if(!insm(M,x,y), break); if(pflg==2, M[y,x]=i, M[y,x]=1));
if(dir=="R", if(xmx>0, x++;xmx--, dir="U";ymx=cnt;y--;ymx--); next);
if(dir=="U", if(ymx>0, y--;ymx--, dir="L";cnt++;xmx=cnt;x--;xmx--); next);
if(dir=="L", if(xmx>0, x--;xmx--, dir="D";ymx=cnt;y++;ymx--); next);
if(dir=="D", if(ymx>0, y++;ymx--, dir="R";cnt++;xmx=cnt;x++;xmx--); next);
);\\fend
\\Plot/Print according to the p-flag(0-real plot,1-"*",2-primes)
if(pflg==0, plotmat(M));
if(pflg==1, for(i=1,n,
for(j=1,n, if(M[i,j]==1, pch="*", pch=" ");
print1(" ",pch)); print(" ")));
if(pflg==2, for(i=1,n,
for(j=1,n, if(M[i,j]==0, pch=pch2, pch=spad(Str(M[i,j]),sz,,1));
print1(" ",pch)); print(" ")));
}
 
{\\ Executing:
plotulamspir(9,1); \\ (see output)
plotulamspir(9,2); \\ (see output)
plotulamspir(100); \\ ULAMspiral1.png
plotulamspir(200); \\ ULAMspiral2.png
}
</syntaxhighlight>
 
{{Output}}
 
<pre>
> plotulamspir(9,1);
*** Ulam spiral: 9x9 matrix, p-flag=1
* *
* *
* * *
* * *
* * * *
* *
* *
* *
* *
> plotulamspir(9,2);
*** Ulam spiral: 9x9 matrix, p-flag=2
61 59
37 31
67 17 13
5 3 29
19 2 11 53
41 7
71 23
43 47
73 79
> plotulamspir(100); \\ ULAMspiral1.png
*** Ulam spiral: 101x101 matrix, p-flag=0
*** matrix(101x101) 1252 DOTS
 
> plotulamspir(200); \\ ULAMspiral2.png
*** Ulam spiral: 201x201 matrix, p-flag=0
*** matrix(201x201) 4236 DOTS
</pre>
 
=={{header|Pascal}}==
Line 1,610 ⟶ 3,697:
 
In the first part of the source are some support routines, from way back in the 1980s, written when the mainframe terminals only offered capitals and the habit lingered. They are there only so as to facilitate some gestures towards checking. The remainder is simple enough, and uses complex numbers to follow the spiral, which of course have to be implemented via ad-hoc code as they're not supported by the compiler. The scheme could be recast into the (line,column) form, counting downwards for the screen line, but array(i,j) = (x,y) means less standing upside down when devising the arithmetic for the directions, at the cost of a "downto" loop for output. An even more tricky scheme would be to ascertain N from (line,column) as the lines were written rather than compute the whole spiral first. Such a function exists.
<syntaxhighlight lang="pascal">
<lang Pascal>
Program Ulam; Uses crt;
{Concocted by R.N.McLean (whom God preserve), ex Victoria university, NZ.}
Line 1,797 ⟶ 3,884:
Until (wot <= 0) or (wot > Mstyle); {Alas, "Enter" must be pressed.}
END.
</syntaxhighlight>
</lang>
=== using FreePascal ===
{{works with|Free Pascal|3.2.0 }}
<syntaxhighlight lang="pascal">
PROGRAM Ulam.pas;
 
=={{header|Perl 6}}==
<lang perl6>sub MAIN($max = 160, $start = 1) {
(my %world){0}{0} = 0;
my $loc = 0+0i;
my $dir = 1;
my $n = $start;
my $side = 0;
 
{$IFDEF FPC}
while ++$side < $max {
{$mode objfpc}{$H+}{$J-}{R+}
step for ^$side;
{$ELSE}
turn-left;
{$APPTYPE CONSOLE}
step for ^$side;
{$ENDIF}
turn-left;
}
 
braille-graphics %world;
 
(*)
sub step {
Free Pascal Compiler version 3.2.0 [2020/06/14] for x86_64
$loc += $dir;
The free and readable alternative at C/C++ speeds
%world{$loc.im}{$loc.re} = $n if (++$n).is-prime;
compiles natively to almost any platform, including raspberry PI
}
 
https://www.freepascal.org/advantage.var
sub turn-left { $dir *= -i; }
(*)
sub turn-right { $dir *= i; }
 
USES
Crt,
SysUtils ;
 
CONST
(*)
Only odd numbers work
(*)
SIZE = 9 ;
MSIZE = SIZE * ord ( Odd ( SIZE ) ) ;
 
TYPE
D2Arr = array of array of string ;
 
 
FUNCTION IsPrime ( n: integer ): boolean ;
 
VAR
i: integer;
 
BEGIN
 
IF ( n < 2 ) THEN Exit ( False ) ;
IF ( n = 2 ) THEN Exit ( True ) ;
IF ( n mod 2 = 0 ) THEN Exit ( False ) ;
 
FOR i := 3 TO Trunc ( Sqrt ( n ) ) DO
IF ( n mod i = 0 ) THEN Exit( False ) ;
 
IsPrime := True ;
 
END;
 
 
PROCEDURE Init2DArr ( Arr: D2Arr ) ;
 
VAR
j: integer;
mid: integer = MSIZE div 2 ;
 
BEGIN
 
FOR j:= 1 to MSIZE - mid - 1 DO
BEGIN
Arr [ mid - j ] [ mid - j ] := '.' ;
Arr [ mid - j ] [ mid + j ] := '.' ;
Arr [ mid + j ] [ mid - j ] := '.' ;
Arr [ mid + j ] [ mid + j - 1 ] := '.' ;
END;
 
END;
 
 
PROCEDURE Advance ( var Turn_cnt, x, y: integer ) ;
 
VAR
dir: array [ 0..3, 0..1 ] of shortint =
( ( 1, 0 ), ( 0, -1 ), ( -1, 0 ), ( 0, 1 ) ) ;
 
BEGIN
 
x := Abs ( x + dir [ Turn_cnt mod 4 ][ 0 ] ) ;
y := Abs ( y + dir [ Turn_cnt mod 4 ][ 1 ] ) ;
 
END;
 
 
PROCEDURE Add2DArr ( Arr: D2Arr ) ;
 
VAR
 
cnt: integer = 1 ;
Turn_cnt: integer = 0 ;
x: integer = MSIZE div 2 ;
y: integer = MSIZE div 2 ;
 
BEGIN
 
WHILE ( cnt < MSIZE * MSIZE ) DO
BEGIN
 
Advance ( Turn_cnt , x , y ) ;
Inc ( cnt ) ;
 
IF ( Arr [ x ] [ y ] = '.' ) THEN
BEGIN
Arr [ x ] [ y ] := '' ;
inc ( Turn_cnt ) ;
END;
 
IF ( IsPrime ( cnt ) ) THEN
Arr [ x ] [ y ] := IntToStr ( cnt ) ;
 
END;
 
END;
 
 
PROCEDURE Show2DArr ( Arr: D2Arr ; glyph : Boolean ) ;
 
VAR
x, y: integer ;
 
BEGIN
 
WriteLn ;
 
FOR y := Low ( Arr ) TO High ( Arr ) DO
BEGIN
FOR x := Low ( Arr [ y ] ) to High ( Arr [ y ] ) DO
 
IF length ( Arr [ x ] [ y ] ) > 0 THEN
IF glyph THEN Write ( '′' : 3 )
ELSE Write ( Arr [ x ] [ y ] : 3 )
ELSE Write ( ' ' : 3) ;
 
WriteLn;
END;
 
WriteLn;
 
END;
 
 
VAR
Arr: D2Arr ;
 
BEGIN
 
IF ( MSIZE = 0 ) THEN
BEGIN
WriteLn ( 'Only odd numbers work for SIZE' ) ;
Exit;
END;
SetLength ( Arr, MSIZE, MSIZE ) ;
Init2DArr ( Arr ) ;
Add2DArr ( Arr ) ;
Show2DArr ( Arr , False ) ;
Show2DArr ( Arr , True ) ;
 
END.
</syntaxhighlight>JPD 2021/06/14
Output:
61 59
37 31
67 17 13
5 3 29
19 2 11 53
41 7
71 23
43 47
73 79
 
 
, ,
, ,
, , ,
, , ,
, , , ,
, ,
, ,
, ,
, ,
 
=== using FreePascal (short version) ===
{{works with|Free Pascal| 3.2.0 }}
<syntaxhighlight lang="pascal">
PROGRAM Ulam8.pas;
 
{$IFDEF FPC}
{$mode objfpc}{$H+}{$J-}{R+}
{$ELSE}
{$APPTYPE CONSOLE}
{$ENDIF}
 
(*)
Free `translation` from PHIX for the Spiral part
 
Free Pascal Compiler version 3.2.0 [2020/06/14] for x86_64
The free and readable alternative at C/C++ speeds
compiles natively to almost any platform, including raspberry PI *
Can run independently from DELPHI / Lazarus
 
For debian Linux: apt -y install fpc
It contains a text IDE called fp
 
https://www.freepascal.org/advantage.var
 
(*)
 
USES
 
crt;
 
CONST
 
SIZE = 9 ; // `SIZE = 9 : "The Iceskater" ( Obvious when Dutch ) `
n = SIZE * ord ( Odd ( SIZE ) ) ;
 
CrLf = #13#10 ;
 
 
FUNCTION IsPrime ( n: integer ): boolean ;
 
VAR
i: integer;
 
BEGIN
 
IF ( n < 2 ) THEN Exit ( False ) ;
IF ( n = 2 ) THEN Exit ( True ) ;
IF ( n mod 2 = 0 ) THEN Exit ( False ) ;
 
FOR i := 3 TO Trunc ( Sqrt ( n ) ) DO
IF ( n mod i = 0 ) THEN Exit( False ) ;
 
IsPrime := True ;
 
END;
 
 
FUNCTION Spiral ( w, h, x, y : integer ) : integer ;
BEGIN
 
IF ( y > 0 ) THEN
Spiral := w + Spiral ( h - 1, w, y - 1, w - x - 1 )
ELSE
Spiral := x
 
END ;
 
PROCEDURE PrintSpiral ( s : string ) ;
 
VAR
 
h : integer = n ;
i : integer ;
j : integer ;
p : integer ;
w : integer = n ;
 
BEGIN
FOR i := h - 1 DOWNTO 0 DO
BEGIN
FOR j := w - 1 DOWNTO 0 DO
BEGIN
 
p := w * h - Spiral ( w, h, j, i ) ;
IF IsPrime ( p ) THEN
IF ( s = '' ) THEN Write ( p:3 ) ELSE Write ( '`':3 )
ELSE Write ( ' ':3 )
 
END;
WriteLn ;
END ;
END ;
 
BEGIN
 
IF ( n = 0 ) THEN
BEGIN
WriteLn ( 'Only odd numbers work for SIZE' ) ;
Exit;
END;
 
PrintSpiral ( '' ) ;
WriteLn ( CrLf ) ;
PrintSpiral ( 'Symbol' ) ;
 
END.
</syntaxhighlight>JPD 2021/07/04
Output:
61 59
37 31
67 17 13
5 3 29
19 2 11 53
41 7
71 23
43 47
73 79
 
 
, ,
, ,
, , ,
, , ,
, , , ,
, ,
, ,
, ,
, ,
 
=={{header|Perl}}==
{{trans|python}}{{libheader|ntheory}}
<syntaxhighlight lang="perl">use ntheory qw/is_prime/;
use Imager;
 
my $n = shift || 512;
my $start = shift || 1;
my $file = "ulam.png";
 
sub cell {
my($n, $x, $y, $start) = @_;
$y -= $n>>1;
$x -= ($n-1)>>1;
my $l = 2*(abs($x) > abs($y) ? abs($x) : abs($y));
my $d = ($y > $x) ? $l*3 + $x + $y : $l-$x-$y;
($l-1)**2 + $d + $start - 1;
}
 
my $black = Imager::Color->new('#000000');
sub braille-graphics (%a) {
my $white = Imager::Color->new('#FFFFFF');
my ($ylo, $yhi, $xlo, $xhi);
my $img = Imager->new(xsize => $n, ysize => $n, channels => 1);
for %a.keys -> $y {
$img->box(filled=>1, color=>$white);
$ylo min= +$y; $yhi max= +$y;
for %a{$y}.keys -> $x {
$xlo min= +$x; $xhi max= +$x;
}
}
 
for $ylo,my $yloy + 4(0 ...^ * > $yhi n-> \y1) {
for $xlo,my $xlox + 2(0 ...^ * > $xhi n-> \x1) {
my $cellv = 0x2800cell($n, $x, $y, $start);
$cellimg->setpixel(x +=> 1$x, y => if %a{$y, +color 0}{x=> +$black) 0}if is_prime($v);
}
$cell += 2 if %a{y + 1}{x + 0};
}
$cell += 4 if %a{y + 2}{x + 0};
 
$cell += 8 if %a{y + 0}{x + 1};
$img->write(file => $file) or die "Cannot write $file: ", $img->errstr, "\n";</syntaxhighlight>
$cell += 16 if %a{y + 1}{x + 1};
$cell += 32 if %a{y + 2}{x + 1};
$cell += 64 if %a{y + 3}{x + 0};
$cell += 128 if %a{y + 3}{x + 1};
print chr($cell);
}
print "\n";
}
}</lang>
{{out}}
Creates an image file <tt>ulam.png</tt> in current directory similar to the one on MathWorld. The square dimension can be optionally specified.
<pre>⠔⠀⠀⠀⢐⠀⠁⠀⠀⠀⢐⠁⠀⢀⠀⠄⠄⠀⢀⠀⠀⠅⢀⠁⢅⢄⠀⢀⠔⠁⠀⠀⠀⢀⢀⠀⠀⠀⠁⢀⢀⠀⠀⢔⠁⢔⠄⠀⢄⠐⠀⠀⢀⠁⠐⠄⠀⢑⠄⠁⠄⠀⠁⠄⠀⠀⠀⢐⠀⠄⠐⠀⢁⢀⠀⠀⠄⠀⢕⠐
 
⠄⠁⠁⠄⠀⠄⢀⠀⠐⠀⠀⠁⢁⢀⠐⠀⠀⠀⢁⠐⠄⠀⠀⠔⠀⢐⠁⠄⠀⠑⠀⢀⠁⠀⠐⠐⠁⠀⠄⠀⢀⠀⠀⠀⠐⠀⠐⠀⠅⠀⠀⢄⢀⠐⠁⠐⠄⠁⢀⠀⠀⠐⠁⠀⠀⠄⢄⠀⠕⠁⠀⠐⢄⠀⠀⢀⠐⠄⠁⠀
=={{header|Phix}}==
⠀⠀⢀⠁⢀⠀⠑⢀⠀⠄⠀⠀⠅⢑⠀⠁⠐⠀⠀⠐⠀⠄⠁⢄⠀⢑⠀⠄⢑⠀⠁⠀⢀⠑⢐⠀⠁⢀⠄⠐⢀⠄⠁⠀⠀⠀⠀⢀⠄⠀⠀⠑⠀⢀⠔⢁⠀⠀⠀⠀⠐⠁⠀⠑⢀⠀⠐⠀⢄⠔⢐⠄⠅⠐⠀⠅⢁⠀⠁⠁
<!--<syntaxhighlight lang="phix">(phixonline)-->
⠅⢀⠄⠑⠀⠀⠅⠄⠀⢐⠐⠀⠀⠄⠀⢁⠄⠀⢔⢀⠁⠀⠔⠁⠑⢐⠀⠐⠀⠁⢑⠀⠀⢁⠀⠀⠄⠀⠀⠑⢀⠀⠄⠔⠁⠀⠄⠀⠐⢀⠀⠀⠔⠁⠀⠐⠀⠀⠐⠁⠐⠀⠀⢀⠄⠁⢁⠀⠀⠐⠀⠁⢐⠀⠐⠀⠄⠑⠐⠄
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
⠀⠀⠀⢐⠑⠑⢀⠁⠑⢀⠐⠀⠄⠀⠀⢀⢐⠕⠄⠀⠀⠀⠐⠀⠀⢀⠄⠀⠀⠀⠄⠐⠐⠀⠀⠁⢄⠐⠅⢀⠐⠄⠁⠐⠀⠅⢀⠐⢁⢀⠀⠁⠐⠕⠀⠀⠀⠀⢐⠀⠅⠐⠔⢁⠀⠐⠅⠐⠄⢀⠀⢄⠀⢀⠄⠀⠀⢀⠁⠐
<span style="color: #008080;">function</span> <span style="color: #000000;">spiral</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">w</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">h</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">y</span><span style="color: #0000FF;">)</span>
⢀⠀⠀⢀⠁⠀⠀⠀⢁⠁⠐⠀⠁⢐⢀⠀⠁⠀⠔⠁⢄⠁⠁⠄⠀⢀⠄⠀⢐⠀⠔⠁⢀⠕⠁⢀⠁⠀⢀⠔⢐⠀⠀⠁⢀⠀⠀⢀⠔⠀⠄⠄⠁⠀⠄⢐⠄⠁⢁⠀⠄⠀⠀⠄⠀⢄⠀⢀⢀⠁⠄⢀⠄⠀⢀⠁⢁⠀⠀⠀
<span style="color: #008080;">return</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">y</span><span style="color: #0000FF;">?</span><span style="color: #000000;">w</span><span style="color: #0000FF;">+</span><span style="color: #000000;">spiral</span><span style="color: #0000FF;">(</span><span style="color: #000000;">h</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">w</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">w</span><span style="color: #0000FF;">-</span><span style="color: #000000;">x</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">):</span><span style="color: #000000;">x</span><span style="color: #0000FF;">)</span>
⠁⠄⠀⠀⠄⠀⠄⠀⠄⠑⢄⠔⠁⠀⠁⠀⠐⠀⠀⠀⠀⠀⢀⠀⠀⠄⠁⢁⠐⠀⠀⢀⠀⠄⠐⠀⢐⠀⠁⠀⠀⠁⠁⠄⠁⢄⠔⠀⠐⠀⠀⠔⢄⠀⠀⢐⠀⢅⠀⠁⢀⠀⠀⠀⠀⠀⠄⠀⠐⠀⠀⠀⠄⠀⠀⠀⠐⠀⠄⠄
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
⠀⠑⠐⠔⠀⢀⢀⠀⢁⠔⠁⢁⠄⠁⠀⠀⠀⠅⠀⢀⠀⠁⢀⠀⢄⠀⠀⠀⠐⠀⢀⠐⠁⢀⠀⠀⠀⢀⠁⠀⠐⠀⠄⢀⠔⢁⠀⠀⢅⠐⠑⠅⠀⠐⠀⢀⠁⢄⠀⠀⢁⠐⠄⠀⠐⢕⢀⠁⢀⠁⠑⠅⠀⢁⠐⠀⠁⠀⢁⢐
⢀⠁⠄⠀⠀⢄⠁⠄⠀⠀⠐⠅⠁⠁⢀⢀⢅⠄⠐⢁⠀⠄⠀⠄⠅⠑⢀⠔⢀⠀⠀⢁⠀⠕⠐⠀⠀⠐⢄⠐⢀⠄⠀⠁⢀⠁⢀⠀⠄⢀⠀⠀⠀⢀⠑⢐⠀⠀⠁⠄⠐⠁⠄⠄⠀⠀⠐⢄⢀⠀⠄⠄⠀⠀⠀⠄⢄⢀⠄⠀
<span style="color: #004080;">integer</span> <span style="color: #000000;">w</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">9</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">h</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">9</span>
⠐⠄⠐⠁⠀⠔⠑⠀⠀⠐⠀⠀⠑⠀⠐⠄⠀⠀⠐⠀⠁⢀⠄⠀⠀⢐⠀⠔⠀⠀⢄⠄⠁⢐⠀⠀⢄⠔⠀⢀⢐⠁⠅⢀⠀⠄⠐⠀⢐⠀⠁⢕⠄⠀⠀⢔⠁⠀⢐⠀⢀⠄⠑⠄⠀⠀⠄⠀⠀⠄⠐⠁⠄⠀⠐⠔⠄⠀⠀⠀
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">h</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">0</span> <span style="color: #008080;">by</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
⢀⠐⢀⢐⠀⠀⠄⠑⠑⠐⠐⠀⠔⠑⠀⠐⠀⢀⠀⠀⢀⠄⠀⠁⢄⠀⠁⠀⢀⠁⢀⠀⠀⠀⠐⠄⠁⢐⠔⠅⢐⠅⠀⠀⠅⠀⠀⠀⠁⠀⠔⠄⠀⠔⢀⠀⠄⢁⠐⢁⢀⢁⢀⢀⢁⠄⠁⢀⠀⠀⢁⢑⠀⢀⢐⠁⠀⠀⠀⠁
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">w</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">0</span> <span style="color: #008080;">by</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
⠀⠄⠅⠀⠁⠅⠁⢁⠄⠀⠀⢀⠀⢄⠀⠁⠁⢁⠀⠄⢅⢁⠄⠄⠐⢀⢀⠄⠁⠀⠀⠀⢄⠔⠁⢀⠐⠁⠄⠐⠀⠀⠁⢐⠀⠀⢀⢀⠀⠀⠀⠐⠀⠄⠐⠀⠀⠁⠄⠀⠁⠀⠀⠁⢄⠀⠁⢅⠀⠄⠁⠀⠁⠅⢀⠀⠀⠀⠐⠁
<span style="color: #004080;">integer</span> <span style="color: #000000;">p</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">w</span><span style="color: #0000FF;">*</span><span style="color: #000000;">h</span><span style="color: #0000FF;">-</span><span style="color: #000000;">spiral</span><span style="color: #0000FF;">(</span><span style="color: #000000;">w</span><span style="color: #0000FF;">,</span><span style="color: #000000;">h</span><span style="color: #0000FF;">,</span><span style="color: #000000;">j</span><span style="color: #0000FF;">,</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
⠁⠀⠀⠀⠀⠀⠀⢄⠀⠐⢀⠀⠐⠄⠄⠁⠀⠔⠔⠄⠀⠁⠀⠐⠄⢀⠀⠄⠔⠀⠁⠀⠀⢐⢔⠁⠅⠀⠀⢐⠀⠀⠄⠄⠀⠑⠔⠀⠅⢀⠁⠔⢀⠀⢔⠀⠁⠐⠐⠐⢐⠔⠀⠐⠀⠐⠀⠀⠐⢐⠄⠐⠐⠀⠑⢐⠐⠑⠐⠐
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"o "</span><span style="color: #0000FF;">[</span><span style="color: #000000;">2</span><span style="color: #0000FF;">-</span><span style="color: #7060A8;">is_prime</span><span style="color: #0000FF;">(</span><span style="color: #000000;">p</span><span style="color: #0000FF;">)])</span>
⢀⠁⠁⠀⠀⢑⢀⠀⠑⢀⠀⢀⠀⠀⠁⢔⠀⠀⠀⠀⢀⢀⠁⠁⢄⠀⢁⠀⠀⠐⠁⢀⠐⢁⠐⠐⢁⠐⠀⢄⠐⠅⠀⢐⠄⢁⢀⠐⠄⠐⠐⠀⠀⠔⠀⠑⢔⢀⠑⠀⠀⠐⠑⠀⠀⠐⢀⢀⠑⠀⠐⢀⠀⠁⠐⠁⠀⢁⠀⠀
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
⠀⠔⠀⢀⠀⠀⢀⠑⠄⠁⠄⠄⢀⠐⠁⠁⠅⠁⢁⢀⠁⠀⢐⠀⠁⠅⢀⢁⠀⢀⠑⢑⠄⠀⠀⠄⠀⠁⢄⠀⢐⠄⠁⠑⢀⠅⢑⠀⠀⠀⠄⠄⢄⠄⠕⢀⠀⠔⢄⢀⠀⠀⠀⠁⢄⠄⠀⠁⠀⠐⠄⠀⠁⢀⠄⠔⠁⠀⠁⠄
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">'\n'</span><span style="color: #0000FF;">)</span>
⠀⠀⠐⠀⠄⠀⠀⢀⠄⠄⢄⠔⠐⢄⠀⠀⠄⠀⠀⠀⠀⠀⢄⠔⠐⠀⠔⠐⠀⠀⠔⠀⠀⢕⢔⠀⠁⢐⠁⢑⠐⠁⠀⠀⠀⢄⠀⠀⢅⠐⠑⠐⠀⠀⢐⠔⠀⠄⠀⠑⢔⠀⠀⠔⠀⠁⢀⠄⠀⠀⠀⠀⠀⠐⠀⠀⠐⠀⠐⠀
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
⠄⠐⠀⠄⠀⢀⠐⠀⢀⢐⠀⢀⠄⠀⢐⠀⠀⠀⠀⠐⠐⢄⠀⠀⠔⠀⢀⠀⠀⢐⢔⠀⢀⢄⠀⠄⢀⢀⠐⠁⢐⠅⠅⢀⠑⠄⠐⠐⠀⢀⠀⠁⠁⠑⠀⢁⠅⠀⠁⠄⠀⠁⠀⠀⠁⠁⠁⠐⠑⠁⠁⠀⢀⠐⢀⢀⠀⠁⠀⢀
<!--</syntaxhighlight>-->
⢁⢀⠄⠁⠐⠀⢁⠀⠀⠀⠀⠁⠀⢑⠀⢁⠐⠀⠀⠀⢁⠁⢐⠀⢀⠀⠀⠀⢕⢄⢁⢑⠄⠀⠔⢀⠐⠁⢀⠄⠐⠄⠄⢑⢄⠅⢄⠀⠁⢁⢀⠐⠁⢀⠀⠄⠀⠐⠀⠀⠀⢀⠀⠁⢄⠀⠄⠀⢀⠅⢁⠀⠀⢀⠀⠅⠄⠀⠑⠀
{{out}}
⠁⠄⠄⠁⠄⠀⠀⠀⠀⠁⠀⠄⠁⠀⠀⠄⠀⠀⠁⠄⠀⠁⠄⠀⠀⠄⠄⠄⠀⠀⠄⠀⠄⠁⠄⠀⠅⠄⠁⢕⢐⠀⢀⠔⠀⠔⠄⠑⠐⠀⠑⢔⠐⠁⠐⠐⠀⢄⠐⠐⠄⠀⠀⠀⠔⠑⠄⠄⠀⠀⠀⠀⢀⠄⠀⠀⠀⠁⢐⠔
<pre>
⠐⠀⠑⢐⠁⠀⢐⠑⢁⢀⠐⢀⢐⠑⠁⠀⠀⢀⠀⠁⠑⠀⠑⢐⢀⠑⢐⠀⠁⢑⠀⠑⠐⠐⠐⠑⢐⠑⢑⠄⣔⢅⢁⢁⠐⢀⢁⢅⠁⠐⢐⠀⠀⠄⢀⢐⢅⢁⠀⠀⠀⠀⠐⠁⢁⠔⢀⢑⠁⢁⠐⢀⠀⠀⢄⢀⢁⢅⢀⠀
o o
⢀⠀⠀⠁⠀⠀⠀⢐⢀⠁⠀⠀⠁⠀⠅⠀⠔⢁⢀⠀⠀⠀⢁⢁⠁⢐⠀⢀⠅⠅⢀⠀⠄⢁⠄⢄⠀⢕⠅⠑⢄⠀⠄⢄⢀⠄⢀⠄⠄⠀⢄⠀⠄⢄⠀⠀⢀⠄⢀⢀⠄⠀⠄⠄⠀⢀⠀⢄⠄⠀⢄⢀⠄⢀⢀⠄⠀⠄⠀⢀
o o
⠐⢄⠀⠄⠀⠄⠐⠀⠀⠁⢀⠀⠅⠀⠄⠄⠀⠀⠀⢀⠔⠕⠄⠄⠑⠀⠀⠁⠀⠐⠔⢄⠀⠀⢄⠐⠔⢀⠁⢐⢀⠐⠄⠐⠁⠀⠄⠐⠐⠄⠁⠀⠐⠀⠄⠀⠑⠄⠐⠀⠀⠐⠀⠔⠀⠁⠔⠀⠁⠀⠀⠑⠄⠔⠀⠀⠀⠑⠐⠀
o o o
⠀⠀⢀⠄⠐⠀⠀⠀⢀⠄⠀⢑⢀⠁⠐⢀⠑⠀⠔⠐⢁⢐⠀⠐⢀⠀⠑⢐⠀⠀⢀⠐⢐⢔⠐⠄⢀⠁⠁⢐⠑⢄⢄⠑⠀⠁⠐⠐⢁⠐⠑⢁⠑⢀⢀⢀⠐⠁⢐⢐⠀⠐⠐⠀⢀⠑⢁⠁⠀⠀⠀⠑⠀⠁⢐⢀⠑⠀⢀⢀
o o o
⠁⢀⠀⠀⢁⠀⠀⠅⠀⠀⠅⠀⠀⠐⢀⢀⢀⠄⠀⠅⠀⢁⠔⠀⠁⢁⠁⠁⠑⢄⠀⠁⠁⢀⢀⠄⠑⢔⠀⠐⠔⠁⠀⠄⠀⠑⢀⠀⠕⠄⠀⠀⠄⢀⠀⠁⢄⠁⢄⠄⠐⠄⢄⠔⠀⠀⠐⠁⢀⠐⠀⠀⠅⠀⠀⠔⠀⢀⠁⠀
o oo o
⠀⢄⠐⠁⠀⠐⠕⠀⠄⠐⠀⠐⠀⢀⠐⠐⠀⠀⠅⠀⠄⠁⢀⠄⠀⠄⠔⠑⢀⠀⠅⠀⠅⠄⠀⠄⠁⢀⠄⠀⢀⠀⢁⢀⠕⠀⠀⠑⠀⠐⠀⢄⠐⠁⢄⠄⠁⠐⠄⠐⢀⠀⠁⠄⠔⠀⢄⠀⠁⠄⠔⠁⢐⠄⠐⠀⠀⠑⢀⠔
o o
⢀⠐⢀⠀⠀⠐⠄⠁⠐⠄⠐⠀⢀⠑⠁⠄⠀⠁⠐⠀⢀⠀⠁⢀⠀⠐⠐⠔⠁⢀⠀⠑⠀⠀⠐⠀⢔⠑⠀⢐⠀⢁⢀⠐⠀⢀⠐⢀⠄⠁⢄⠁⠀⠀⠁⠀⠀⠀⢐⢀⢁⢑⠀⢀⠑⠐⠁⠀⢀⢀⠀⠁⢀⢀⠀⠀⠐⢀⠀⠐
o o
⢀⢁⠀⠀⢑⢅⢁⢄⢀⢀⠅⠀⠀⠄⢀⢁⢐⢁⢀⢅⢄⠀⠀⢀⢀⠐⠅⠁⠀⠀⢁⠐⠀⢀⠀⠀⠐⢀⠀⢀⠄⠅⠐⢐⠀⠀⠔⠁⠑⠐⠄⠀⠄⠀⠅⠁⠄⠐⠀⠀⠁⠁⠀⠄⠅⠀⠀⠄⠄⠅⠀⠄⠀⠄⠀⠁⠀⠀⠔⠀
o o
⠁⠀⠀⠁⠀⠀⠀⢀⠄⠀⠀⠀⠀⠄⠄⠀⢀⠀⠐⢀⠀⠀⢄⠔⠄⠀⠄⠀⠀⠔⠕⢀⠔⠀⠀⠄⠄⠀⠁⠐⠀⠀⠕⢀⠕⠁⠀⠁⢑⠀⠀⢀⢀⠐⠄⠀⠑⠀⠀⠁⢄⠔⠑⢐⠀⠑⢄⠐⠀⠀⠐⠀⠀⠀⠀⠀⠄⠁⢀⠄
o o
⠀⠁⠐⠀⠁⠀⠄⠀⠑⠀⠀⢀⠀⠐⠀⠄⠀⠑⠀⠀⢐⠀⠁⢅⠀⠀⠀⠐⠀⢀⠄⠀⢁⢄⠀⠁⠔⠑⠄⠀⠑⢄⠔⠁⢀⠀⠀⢄⠄⠀⠀⠐⠁⠁⢀⠐⠄⠀⠁⠐⠁⢀⢑⠁⠐⠐⢀⠑⠔⠀⠁⠀⢁⢀⠄⠁⢐⠀⠀⠀
⠀⠅⠁⢀⠐⠀⠁⠐⠀⠁⠐⢄⠀⢄⢀⠀⠄⢀⠁⢁⠄⠀⠐⠀⢑⠄⠀⠑⠐⠀⠁⠀⠁⠐⠐⠀⠁⠄⠄⢀⠄⠁⠐⢀⠄⠐⠀⠄⠀⠄⠀⠀⢀⠄⢀⢐⠀⠑⠀⠀⠄⢄⢄⠀⢅⠀⠀⠄⠀⠅⠀⠄⠐⢀⠀⠔⠅⠀⠄⢁
⠄⠀⠄⠄⠀⠄⠀⢀⠀⠐⠀⠀⠁⠀⠔⠄⠀⠀⠁⠀⠄⢄⠀⠐⠀⠀⠄⢑⠀⠁⠅⠀⠁⠀⢀⠄⠑⢀⠄⢀⢀⠔⢀⠀⠑⠄⠀⠅⠀⠀⠅⢕⠀⠐⢐⠀⠄⠕⠀⠀⢀⠀⠀⢀⠀⠁⠀⠀⠐⢀⠐⠁⢀⠔⠁⢐⠀⠀⠐⠀
⠀⠐⢁⢀⠐⠀⢀⠁⠀⠀⠁⠑⠄⠀⢁⠐⠁⠅⢀⠐⢀⠄⠀⠀⠐⠀⠅⢀⠐⢀⢀⠁⠅⢀⠀⠄⠔⠑⠁⠀⠁⠀⠐⠁⢀⠀⠀⢀⠀⠐⠄⠔⠐⠁⢄⠀⠅⢄⠑⠀⢀⠐⠀⠀⢁⢀⠀⢀⠁⢀⠁⠅⠁⠀⠁⠀⠀⠄⠀⠁
⠀⠀⢀⠀⠄⢁⠀⠀⠄⠀⢁⢁⠀⠀⠀⠐⠀⠄⠀⠐⠀⢀⢀⠁⠁⠄⠄⢀⠀⠀⠑⢀⠀⠑⠐⠁⠀⠀⠁⢐⠄⠀⢀⠐⠄⠐⢀⠁⠑⢀⠀⠀⠐⠀⢑⠄⠀⠁⠀⠅⠐⠄⠀⠀⠄⠀⠄⠁⠀⠄⢁⢀⠁⠁⠄⠀⠀⠀⠀⢄
⠑⠀⠀⠀⢀⠀⠁⠄⠐⠀⠀⠄⢄⠀⠐⠐⠀⠑⢁⠀⠔⠀⠀⠀⠀⠀⠕⢄⠀⠐⠀⢀⠔⠅⢀⠀⠐⠀⠅⢐⠀⠕⠐⢀⠀⠔⠀⠅⠀⠀⠀⠄⢀⠁⢀⠀⠀⠔⠀⠐⠁⢀⠀⠁⢀⠁⠀⠐⠐⠄⠐⠐⠄⠀⠀⠀⠀⠀⠔⠐
⠐⠀⢐⠀⠀⠀⢀⠀⠐⠐⠀⠀⠐⠀⠄⢀⠁⢄⠀⠑⢀⠀⠐⢀⢄⠀⠀⢀⠀⢅⢔⠁⠄⠐⠀⠁⠀⠑⠀⠀⠐⠁⠄⠀⢁⢀⠀⠁⠐⠁⠀⠀⠀⠀⠀⠀⠀⠀⠐⢀⠄⠀⢀⢔⠑⢅⠀⠐⢄⠁⢀⠄⢁⢀⠐⠀⠀⢀⢀⢑
⠀⠄⠅⢀⠁⠀⠀⠅⠁⠀⢄⠀⠁⠐⠁⢀⠀⠀⠀⠀⠀⠑⠀⠄⢀⠀⠀⢀⠐⠀⠀⢀⠁⠐⢀⠄⠁⢔⠄⠀⠄⠄⠑⠄⠁⠀⠀⠁⠐⠐⠄⠁⢄⠀⢀⠄⠁⠀⠔⠁⢀⠐⠄⠀⠀⠀⢁⢐⠀⠀⠄⠀⠀⢀⠀⠅⠀⠀⠀⠀
⠔⠀⠄⠀⢀⠄⠁⢀⠁⠄⠀⠀⠑⠀⠐⠁⠀⠐⠑⢀⠄⠄⠀⠀⢄⠀⠔⠔⢀⠀⠁⠀⠔⠀⢀⠄⠀⠀⠁⢐⠀⠑⠀⠀⠀⢅⠀⠀⢀⠀⠁⠄⠀⠁⢀⠀⠔⠐⠀⠀⢅⠀⠐⢀⠀⠀⠄⢀⠐⠔⠀⠁⠄⠀⠁⠀⠔⠐⠀⠀
⠀⠐⢀⠐⠀⠁⢀⠀⠀⠐⠐⢀⢄⠐⢄⠐⠀⠅⠀⠁⠁⠄⠐⢁⠄⠀⠀⢄⠀⠅⠔⠀⢁⠀⠐⠄⢀⠀⠁⠀⠐⠀⢀⠑⢀⠄⠀⠅⠀⠀⠅⠀⠀⢀⢔⠐⠄⠀⠁⠀⠐⠀⠀⢀⠑⠀⠄⠐⢁⢀⠀⢄⢄⠁⢀⠀⢐⠐⠁⠁
⠁⠄⠄⠀⠀⠁⠀⢐⠀⠐⠀⠄⢑⠀⠀⠑⠄⠁⢁⢀⠀⢑⠔⠁⠀⠄⠄⠀⢀⠀⠑⠔⠁⢁⠀⠄⢁⠔⠀⢀⠔⠀⢐⠀⠀⠀⠄⠄⠀⠐⠁⢁⠔⠁⠐⠐⠁⢀⢀⠀⠁⠔⠀⠀⠀⠅⠁⠀⠄⠀⠔⠁⢑⠀⠀⠀⠀⠀⠐⠀
⠁⠀⠅⠐⠀⠁⠀⠀⠐⠁⠀⠀⠕⠀⠀⠅⠀⠐⠀⠀⠕⠁⠀⠄⠅⠀⠀⠐⠀⠐⠅⠀⠀⠄⠀⠀⠀⠀⠀⠐⠀⠀⠀⠀⠁⠀⠀⠀⠄⠀⠐⠁⠀⠄⠁⠀⠁⠄⠀⠐⠄⠀⠅⠀⠀⠔⠁⠀⠀⠕⠀⠀⠀⠀⠀⠁⠀⠁⠀⠀
</pre>
For something that almost fills your entire screen (not pwa/p2js compatible), change the definition of w and h to
<!--<syntaxhighlight lang="phix">-->
<span style="color: #004080;">sequence</span> <span style="color: #000000;">vc</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">video_config</span><span style="color: #0000FF;">()</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">w</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">vc</span><span style="color: #0000FF;">[</span><span style="color: #000000;">VC_SCRNCOLS</span><span style="color: #0000FF;">]-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">h</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">vc</span><span style="color: #0000FF;">[</span><span style="color: #004600;">VC_SCRNLINES</span><span style="color: #0000FF;">]-</span><span style="color: #000000;">1</span>
<!--</syntaxhighlight>-->
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(load "@lib/simul.l")
 
(de ceil (A)
Line 1,940 ⟶ 4,315:
(ulam 9) )
 
(bye)</langsyntaxhighlight>
{{out}}
<pre>
Line 1,952 ⟶ 4,327:
_ . _ _ _ . _ _ _
. _ _ _ _ _ . _ _
</pre>
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
function New-UlamSpiral ( [int]$N )
{
# Generate list of primes
$Primes = @( 2 )
For ( $X = 3; $X -le $N*$N; $X += 2 )
{
If ( -not ( $Primes | Where { $X % $_ -eq 0 } | Select -First 1 ) ) { $Primes += $X }
}
# Initialize variables
$X = 0
$Y = -1
$i = $N * $N + 1
$Sign = 1
 
# Intialize array
$A = New-Object 'boolean[,]' $N, $N
 
# Set top row
1..$N | ForEach { $Y += $Sign; $A[$X,$Y] = --$i -in $Primes }
 
# For each remaining half spiral...
ForEach ( $M in ($N-1)..1 )
{
# Set the vertical quarter spiral
1..$M | ForEach { $X += $Sign; $A[$X,$Y] = --$i -in $Primes }
# Curve the spiral
$Sign = -$Sign
# Set the horizontal quarter spiral
1..$M | ForEach { $Y += $Sign; $A[$X,$Y] = --$i -in $Primes }
}
# Convert the array of booleans to text output of dots and spaces
$Spiral = ForEach ( $X in 1..$N ) { ( 1..$N | ForEach { ( ' ', '.' )[$A[($X-1),($_-1)]] } ) -join '' }
return $Spiral
}
 
New-UlamSpiral 100
</syntaxhighlight>
{{out}}
<pre>
. . . . . . . . .
. . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . .
. . . . . . . .. . . . . . . . . . . . .
. . . . . . . . . .
. . . .
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . .
</pre>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python"># coding=UTF-8
from __future__ import print_function, division
from math import sqrt
Line 1,990 ⟶ 4,512:
show_spiral(9, symbol='', space=' - ')
# for filling giant terminals
#show_spiral(1001, symbol='*', start=42)</langsyntaxhighlight>
{{out}}
<pre>
Line 2,013 ⟶ 4,535:
- 43 - - - 47 - - -
73 - - - - - 79 - -
</pre>
 
=={{header|Quackery}}==
 
<code>spiral</code> is defined at [[Spiral matrix#Quackery]].
 
<code>isprime</code> is defined at [[Primality by trial division#Quackery]].
 
<syntaxhighlight lang="Quackery"> 32 spiral
witheach
[ witheach
[ 1024 swap -
isprime iff
say " o"
else say " ." ]
cr ]</syntaxhighlight>
 
{{out}}
 
<pre>
. . . o . o . . . . . o . . . o . . . . . . . . . . . o . . . .
. . . . . . . . . . . . . . o . . . o . o . . . o . . . . . . .
. . . . . . . . . . . . . o . . . o . . . . . . . o . . . o . o
. . o . . . o . . . . . . . . . . . o . o . . . . . o . . . . .
. o . o . . . . . o . o . . . . . o . . . . . o . . . . . . . .
. . . . . . . . . . o . . . . . . . . . . . o . . . o . . . . .
. . . . . o . . . o . . . . . . . o . . . . . o . . . . . . . .
o . . . o . . . . . . . . . o . . . o . o . . . o . o . o . . .
. . . . . . . o . . . . . o . . . . . . . . . o . o . . . o . .
. . o . . . . . o . . . o . o . . . . . . . . . . . . . . . o .
. . . . . . . . . . . . . . . o . o . . . . . o . . . o . . . o
o . . . o . . . o . o . . . o . . . . . . . o . . . o . o . . .
. . . . . . . . . . . . . . . o . o . . . o . . . . . . . . . .
. . . . . . o . . . o . o . . . . . o . o . o . . . . . o . o .
. o . o . o . o . o . o . o . . . o . . . . . . . o . . . . . .
. . . . . . . . . . . . . . o . o . o . . . . . . . . . . . o .
. . . . . . . . . o . . . o . . o o . o . o . o . . . o . o . o
. . o . . . . . . . o . o . o . . . . . . . . . . . . . . . . .
. . . . . . . . . . . o . . . o . . . . . . . . . . . . . . . .
o . . . o . o . . . o . o . . . o . . . o . o . . . o . . . o .
. . . o . . . o . . . o . . . . . o . . . . . o . o . . . o . .
. . . . . . . . . . . . o . . . . . . . . . . . o . . . . . . .
. . . . . . . o . o . . . . . o . . . o . . . o . . . . . . . o
. . . . o . . . o . . . . . . . . . . . o . . . . . . . o . . .
. . . . . o . . . . . o . . . o . o . . . . . . . . . . . . . .
. . . . . . . . . . o . o . . . o . . . . . o . . . o . . . . .
. o . o . o . . . . . . . . . o . o . . . . . o . . . . . o . o
. . o . . . o . . . . . . . . . . . o . o . . . . . . . . . . .
. o . o . . . . . o . . . . . o . . . o . o . . . . . . . . . .
o . . . . . . . o . . . . . . . . . o . . . . . . . o . . . . .
. . . . . . . . . o . o . . . o . o . . . . . . . . . o . . . .
. . . . . . o . . . o . . . . . o . . . . . o . . . . . . . . .
</pre>
 
=={{header|R}}==
My own plotting helper function plotmat() was used and made it possible. You can find it here on RC (Brownian tree in R) .
;Note:
* All pictures are ready to be uploaded, when it would be allowed again.
{{trans|PARI/GP}}
{{Works with|R|3.3.1 and above}}
 
[[File:UlamSpiralR1.png|200px|right|thumb|Output UlamSpiralR1.png]]
[[File:UlamSpiralR2.png|200px|right|thumb|Output UlamSpiralR2.png]]
 
<syntaxhighlight lang="r">
## Plotting Ulam spiral (for primes) 2/12/17 aev
## plotulamspirR(n, clr, fn, ttl, psz=600), where: n - initial size;
## clr - color; fn - file name; ttl - plot title; psz - picture size.
##
require(numbers);
plotulamspirR <- function(n, clr, fn, ttl, psz=600) {
cat(" *** START:", date(), "n=",n, "clr=",clr, "psz=", psz, "\n");
if (n%%2==0) {n=n+1}; n2=n*n;
x=y=floor(n/2); xmx=ymx=cnt=1; dir="R";
ttl= paste(c(ttl, n,"x",n," matrix."), sep="", collapse="");
cat(" ***", ttl, "\n");
M <- matrix(c(0), ncol=n, nrow=n, byrow=TRUE);
for (i in 1:n2) {
if(isPrime(i)) {M[x,y]=1};
if(dir=="R") {if(xmx>0) {x=x+1;xmx=xmx-1}
else {dir="U";ymx=cnt;y=y-1;ymx=ymx-1}; next};
if(dir=="U") {if(ymx>0) {y=y-1;ymx=ymx-1}
else {dir="L";cnt=cnt+1;xmx=cnt;x=x-1;xmx=xmx-1}; next};
if(dir=="L") {if(xmx>0) {x=x-1;xmx=xmx-1}
else {dir="D";ymx=cnt;y=y+1;ymx=ymx-1}; next};
if(dir=="D") {if(ymx>0) {y=y+1;ymx=ymx-1}
else {dir="R";cnt=cnt+1;xmx=cnt;x=x+1;xmx=xmx-1}; next};
};
plotmat(M, fn, clr, ttl,,psz);
cat(" *** END:",date(),"\n");
}
 
## Executing:
plotulamspirR(100, "red", "UlamSpiralR1", "Ulam Spiral: ");
plotulamspirR(200, "red", "UlamSpiralR2", "Ulam Spiral: ",1240);
</syntaxhighlight>
 
{{Output}}
 
<pre>
> plotulamspirR(100, "red", "UlamSpiralR1", "Ulam Spiral: ");
*** START: Sun Feb 12 12:03:34 2017 n= 100 clr= red psz= 600
*** Ulam Spiral: 101x101 matrix.
*** Matrix( 101 x 101 ) 1232 DOTS
*** END: Sun Feb 12 12:03:37 2017
 
> plotulamspirR(200, "red", "UlamSpiralR2", "Ulam Spiral: ",1240);
*** START: Sun Feb 12 12:03:51 2017 n= 200 clr= red psz= 1240
*** Ulam Spiral: 201x201 matrix.
*** Matrix( 201 x 201 ) 4196 DOTS
*** END: Sun Feb 12 12:04:07 2017
</pre>
 
Line 2,019 ⟶ 4,652:
{{trans|Python}}
 
<langsyntaxhighlight lang="racket">#lang racket
(require (only-in math/number-theory prime?))
 
(define ((cell-fn n (start 1)) x y)
(let* ((y (- y (quotient n 2)))
(x (- x (quotient (sub1 n) 2)))
(l (* 2 (if (> (abs x) (abs y)) (abs x) (abs y))))
(d (if (>= y x) (+ (* l 3) x y) (- l x y))))
(+ (sqr (- l 1)) d start -1)))
 
(define (show-spiral n
#:symbol (smb "# ")
#:start (start 1)
#:space (space (and smb (make-string (string-length smb) #\space))))
(define top (+ start (sqr* n n) 1))
(define cell (cell-fn n start))
(define print-cell
Line 2,043 ⟶ 4,676:
(display (if p? (~a #:width max-len i #:align 'right) space))
(display #\space)))))
(for* ((y (in-range 1 (add10 n))) #:when (unless (= y 10) (newline)) (x (in-range 1 (add10 n))))
(define c (cell x y))
(define p? (prime? c))
(print-cell c p?))
(newline))
 
(show-spiral 9 #:symbol #f)
(show-spiral 10 #:symbol "♞" #:space "♘") ; black are the primes
(show-spiral 50 #:symbol "*" #:start 42)
; for filling giant terminals
; (show_spiralshow-spiral 1001 #:symbol "*" #:start 42)</langsyntaxhighlight>
 
{{out}}
<pre>37 __ __ __ __ 61 __ 3159 __ 89__
__ 1737 __ __ __ 13 __ __ 31 __
__67 __ 17 5__ __ 3 __ 2913 __ __
__ 19 __ __ 25 __ 113 __ 5329 __
41__ __ 719 __ __ __ __2 11 __ __53
__ __41 __ 23 7 __ __ __ __ __
4371 __ __ __ 4723 __ __ __ 83__
__ __43 __ __ __ 7947 __ __ __
1173 __ __ __ __ __ __79 __ __
♘♘♘♞♘♞♘♘♘♞
♞♘♘♘♘♘♞♘♞♘
♘♞♘♘♘♞♘♘♘♘
♘♘♞♘♞♘♞♘♘♘
♘♞♘♘♞♞♘♞♘♞
♞♘♞♘♘♘♘♘♘♘
♘♘♘♞♘♘♘♘♘♘
♘♘♘♘♞♘♞♘♘♘
♞♘♘♘♞♘♘♘♞♘
♘♞♘♘♘♘♘♞♘♞
♘♘♘♘♘♞♘♘♘♘
♞♘♞♘♘♘♞♘♘♘
♞♘♘♘♘♘♘♘♘♘
♘♘♘♞♘♞♘♞♘♘
* * * * *
♘♘♞♘♘♞♞♘♞♘
* * * * * * * *
♘♞♘♞♘♘♘♘♘♘
* * * *
♞♘♘♘♞♘♘♘♘♘
* * * * * * * *
♘♞♘♘♘♞♘♘♘♞
* * * * * * * *
♞♘♘♘♘♘♞♘♘♘
* * * * * * * * * *
* * * * * * * * *
* * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * *
* * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * *
* * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * *
* * * * * * *
* * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * *
* * * * * * * * * *
* * * * * * * * *
* * * * * * * *
* * * * * *
* * * * * * * * *
* * * * * * *
* * * * * *
* * * * * * * *
* * * * * *
</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" line>sub MAIN($max = 160, $start = 1) {
(my %world){0}{0} = 0;
my ($n, $dir, $side, $loc) = $start, 1, 0, 0+0i;
 
while ++$side < $max {
step for ^$side; turn-left;
step for ^$side; turn-left;
}
 
braille-graphics %world;
 
sub step {
$loc += $dir;
%world{$loc.im}{$loc.re} = $n if (++$n).is-prime;
}
 
sub turn-left { $dir ×= -i }
sub turn-right { $dir ×= i }
}
 
sub braille-graphics (%a) {
my ($y-lo, $y-hi, $x-lo, $x-hi);
for %a.keys.map(+*) -> \y {
for %a{y}.keys.map(+*) -> \x {
$y-lo min= y; $y-hi max= y;
$x-lo min= x; $x-hi max= x;
}
}
 
for $y-lo, $y-lo + 4 ...^ $y-hi -> \y {
for $x-lo, $x-lo + 2 ...^ $x-hi -> \x {
my $cell = 0x2800;
$cell += 2⁰ if %a{y + 0}{x + 0};
$cell += 2¹ if %a{y + 1}{x + 0};
$cell += 2² if %a{y + 2}{x + 0};
$cell += 2³ if %a{y + 0}{x + 1};
$cell += 2⁴ if %a{y + 1}{x + 1};
$cell += 2⁵ if %a{y + 2}{x + 1};
$cell += 2⁶ if %a{y + 3}{x + 0};
$cell += 2⁷ if %a{y + 3}{x + 1};
print chr($cell);
}
print "\n";
}
}</syntaxhighlight>
{{out}}
<pre>⠔⠀⠀⠀⢐⠀⠁⠀⠀⠀⢐⠁⠀⢀⠀⠄⠄⠀⢀⠀⠀⠅⢀⠁⢅⢄⠀⢀⠔⠁⠀⠀⠀⢀⢀⠀⠀⠀⠁⢀⢀⠀⠀⢔⠁⢔⠄⠀⢄⠐⠀⠀⢀⠁⠐⠄⠀⢑⠄⠁⠄⠀⠁⠄⠀⠀⠀⢐⠀⠄⠐⠀⢁⢀⠀⠀⠄⠀⢕⠐
⠄⠁⠁⠄⠀⠄⢀⠀⠐⠀⠀⠁⢁⢀⠐⠀⠀⠀⢁⠐⠄⠀⠀⠔⠀⢐⠁⠄⠀⠑⠀⢀⠁⠀⠐⠐⠁⠀⠄⠀⢀⠀⠀⠀⠐⠀⠐⠀⠅⠀⠀⢄⢀⠐⠁⠐⠄⠁⢀⠀⠀⠐⠁⠀⠀⠄⢄⠀⠕⠁⠀⠐⢄⠀⠀⢀⠐⠄⠁⠀
⠀⠀⢀⠁⢀⠀⠑⢀⠀⠄⠀⠀⠅⢑⠀⠁⠐⠀⠀⠐⠀⠄⠁⢄⠀⢑⠀⠄⢑⠀⠁⠀⢀⠑⢐⠀⠁⢀⠄⠐⢀⠄⠁⠀⠀⠀⠀⢀⠄⠀⠀⠑⠀⢀⠔⢁⠀⠀⠀⠀⠐⠁⠀⠑⢀⠀⠐⠀⢄⠔⢐⠄⠅⠐⠀⠅⢁⠀⠁⠁
⠅⢀⠄⠑⠀⠀⠅⠄⠀⢐⠐⠀⠀⠄⠀⢁⠄⠀⢔⢀⠁⠀⠔⠁⠑⢐⠀⠐⠀⠁⢑⠀⠀⢁⠀⠀⠄⠀⠀⠑⢀⠀⠄⠔⠁⠀⠄⠀⠐⢀⠀⠀⠔⠁⠀⠐⠀⠀⠐⠁⠐⠀⠀⢀⠄⠁⢁⠀⠀⠐⠀⠁⢐⠀⠐⠀⠄⠑⠐⠄
⠀⠀⠀⢐⠑⠑⢀⠁⠑⢀⠐⠀⠄⠀⠀⢀⢐⠕⠄⠀⠀⠀⠐⠀⠀⢀⠄⠀⠀⠀⠄⠐⠐⠀⠀⠁⢄⠐⠅⢀⠐⠄⠁⠐⠀⠅⢀⠐⢁⢀⠀⠁⠐⠕⠀⠀⠀⠀⢐⠀⠅⠐⠔⢁⠀⠐⠅⠐⠄⢀⠀⢄⠀⢀⠄⠀⠀⢀⠁⠐
⢀⠀⠀⢀⠁⠀⠀⠀⢁⠁⠐⠀⠁⢐⢀⠀⠁⠀⠔⠁⢄⠁⠁⠄⠀⢀⠄⠀⢐⠀⠔⠁⢀⠕⠁⢀⠁⠀⢀⠔⢐⠀⠀⠁⢀⠀⠀⢀⠔⠀⠄⠄⠁⠀⠄⢐⠄⠁⢁⠀⠄⠀⠀⠄⠀⢄⠀⢀⢀⠁⠄⢀⠄⠀⢀⠁⢁⠀⠀⠀
⠁⠄⠀⠀⠄⠀⠄⠀⠄⠑⢄⠔⠁⠀⠁⠀⠐⠀⠀⠀⠀⠀⢀⠀⠀⠄⠁⢁⠐⠀⠀⢀⠀⠄⠐⠀⢐⠀⠁⠀⠀⠁⠁⠄⠁⢄⠔⠀⠐⠀⠀⠔⢄⠀⠀⢐⠀⢅⠀⠁⢀⠀⠀⠀⠀⠀⠄⠀⠐⠀⠀⠀⠄⠀⠀⠀⠐⠀⠄⠄
⠀⠑⠐⠔⠀⢀⢀⠀⢁⠔⠁⢁⠄⠁⠀⠀⠀⠅⠀⢀⠀⠁⢀⠀⢄⠀⠀⠀⠐⠀⢀⠐⠁⢀⠀⠀⠀⢀⠁⠀⠐⠀⠄⢀⠔⢁⠀⠀⢅⠐⠑⠅⠀⠐⠀⢀⠁⢄⠀⠀⢁⠐⠄⠀⠐⢕⢀⠁⢀⠁⠑⠅⠀⢁⠐⠀⠁⠀⢁⢐
⢀⠁⠄⠀⠀⢄⠁⠄⠀⠀⠐⠅⠁⠁⢀⢀⢅⠄⠐⢁⠀⠄⠀⠄⠅⠑⢀⠔⢀⠀⠀⢁⠀⠕⠐⠀⠀⠐⢄⠐⢀⠄⠀⠁⢀⠁⢀⠀⠄⢀⠀⠀⠀⢀⠑⢐⠀⠀⠁⠄⠐⠁⠄⠄⠀⠀⠐⢄⢀⠀⠄⠄⠀⠀⠀⠄⢄⢀⠄⠀
⠐⠄⠐⠁⠀⠔⠑⠀⠀⠐⠀⠀⠑⠀⠐⠄⠀⠀⠐⠀⠁⢀⠄⠀⠀⢐⠀⠔⠀⠀⢄⠄⠁⢐⠀⠀⢄⠔⠀⢀⢐⠁⠅⢀⠀⠄⠐⠀⢐⠀⠁⢕⠄⠀⠀⢔⠁⠀⢐⠀⢀⠄⠑⠄⠀⠀⠄⠀⠀⠄⠐⠁⠄⠀⠐⠔⠄⠀⠀⠀
⢀⠐⢀⢐⠀⠀⠄⠑⠑⠐⠐⠀⠔⠑⠀⠐⠀⢀⠀⠀⢀⠄⠀⠁⢄⠀⠁⠀⢀⠁⢀⠀⠀⠀⠐⠄⠁⢐⠔⠅⢐⠅⠀⠀⠅⠀⠀⠀⠁⠀⠔⠄⠀⠔⢀⠀⠄⢁⠐⢁⢀⢁⢀⢀⢁⠄⠁⢀⠀⠀⢁⢑⠀⢀⢐⠁⠀⠀⠀⠁
⠀⠄⠅⠀⠁⠅⠁⢁⠄⠀⠀⢀⠀⢄⠀⠁⠁⢁⠀⠄⢅⢁⠄⠄⠐⢀⢀⠄⠁⠀⠀⠀⢄⠔⠁⢀⠐⠁⠄⠐⠀⠀⠁⢐⠀⠀⢀⢀⠀⠀⠀⠐⠀⠄⠐⠀⠀⠁⠄⠀⠁⠀⠀⠁⢄⠀⠁⢅⠀⠄⠁⠀⠁⠅⢀⠀⠀⠀⠐⠁
⠁⠀⠀⠀⠀⠀⠀⢄⠀⠐⢀⠀⠐⠄⠄⠁⠀⠔⠔⠄⠀⠁⠀⠐⠄⢀⠀⠄⠔⠀⠁⠀⠀⢐⢔⠁⠅⠀⠀⢐⠀⠀⠄⠄⠀⠑⠔⠀⠅⢀⠁⠔⢀⠀⢔⠀⠁⠐⠐⠐⢐⠔⠀⠐⠀⠐⠀⠀⠐⢐⠄⠐⠐⠀⠑⢐⠐⠑⠐⠐
⢀⠁⠁⠀⠀⢑⢀⠀⠑⢀⠀⢀⠀⠀⠁⢔⠀⠀⠀⠀⢀⢀⠁⠁⢄⠀⢁⠀⠀⠐⠁⢀⠐⢁⠐⠐⢁⠐⠀⢄⠐⠅⠀⢐⠄⢁⢀⠐⠄⠐⠐⠀⠀⠔⠀⠑⢔⢀⠑⠀⠀⠐⠑⠀⠀⠐⢀⢀⠑⠀⠐⢀⠀⠁⠐⠁⠀⢁⠀⠀
⠀⠔⠀⢀⠀⠀⢀⠑⠄⠁⠄⠄⢀⠐⠁⠁⠅⠁⢁⢀⠁⠀⢐⠀⠁⠅⢀⢁⠀⢀⠑⢑⠄⠀⠀⠄⠀⠁⢄⠀⢐⠄⠁⠑⢀⠅⢑⠀⠀⠀⠄⠄⢄⠄⠕⢀⠀⠔⢄⢀⠀⠀⠀⠁⢄⠄⠀⠁⠀⠐⠄⠀⠁⢀⠄⠔⠁⠀⠁⠄
⠀⠀⠐⠀⠄⠀⠀⢀⠄⠄⢄⠔⠐⢄⠀⠀⠄⠀⠀⠀⠀⠀⢄⠔⠐⠀⠔⠐⠀⠀⠔⠀⠀⢕⢔⠀⠁⢐⠁⢑⠐⠁⠀⠀⠀⢄⠀⠀⢅⠐⠑⠐⠀⠀⢐⠔⠀⠄⠀⠑⢔⠀⠀⠔⠀⠁⢀⠄⠀⠀⠀⠀⠀⠐⠀⠀⠐⠀⠐⠀
⠄⠐⠀⠄⠀⢀⠐⠀⢀⢐⠀⢀⠄⠀⢐⠀⠀⠀⠀⠐⠐⢄⠀⠀⠔⠀⢀⠀⠀⢐⢔⠀⢀⢄⠀⠄⢀⢀⠐⠁⢐⠅⠅⢀⠑⠄⠐⠐⠀⢀⠀⠁⠁⠑⠀⢁⠅⠀⠁⠄⠀⠁⠀⠀⠁⠁⠁⠐⠑⠁⠁⠀⢀⠐⢀⢀⠀⠁⠀⢀
⢁⢀⠄⠁⠐⠀⢁⠀⠀⠀⠀⠁⠀⢑⠀⢁⠐⠀⠀⠀⢁⠁⢐⠀⢀⠀⠀⠀⢕⢄⢁⢑⠄⠀⠔⢀⠐⠁⢀⠄⠐⠄⠄⢑⢄⠅⢄⠀⠁⢁⢀⠐⠁⢀⠀⠄⠀⠐⠀⠀⠀⢀⠀⠁⢄⠀⠄⠀⢀⠅⢁⠀⠀⢀⠀⠅⠄⠀⠑⠀
⠁⠄⠄⠁⠄⠀⠀⠀⠀⠁⠀⠄⠁⠀⠀⠄⠀⠀⠁⠄⠀⠁⠄⠀⠀⠄⠄⠄⠀⠀⠄⠀⠄⠁⠄⠀⠅⠄⠁⢕⢐⠀⢀⠔⠀⠔⠄⠑⠐⠀⠑⢔⠐⠁⠐⠐⠀⢄⠐⠐⠄⠀⠀⠀⠔⠑⠄⠄⠀⠀⠀⠀⢀⠄⠀⠀⠀⠁⢐⠔
⠐⠀⠑⢐⠁⠀⢐⠑⢁⢀⠐⢀⢐⠑⠁⠀⠀⢀⠀⠁⠑⠀⠑⢐⢀⠑⢐⠀⠁⢑⠀⠑⠐⠐⠐⠑⢐⠑⢑⠄⣔⢅⢁⢁⠐⢀⢁⢅⠁⠐⢐⠀⠀⠄⢀⢐⢅⢁⠀⠀⠀⠀⠐⠁⢁⠔⢀⢑⠁⢁⠐⢀⠀⠀⢄⢀⢁⢅⢀⠀
⢀⠀⠀⠁⠀⠀⠀⢐⢀⠁⠀⠀⠁⠀⠅⠀⠔⢁⢀⠀⠀⠀⢁⢁⠁⢐⠀⢀⠅⠅⢀⠀⠄⢁⠄⢄⠀⢕⠅⠑⢄⠀⠄⢄⢀⠄⢀⠄⠄⠀⢄⠀⠄⢄⠀⠀⢀⠄⢀⢀⠄⠀⠄⠄⠀⢀⠀⢄⠄⠀⢄⢀⠄⢀⢀⠄⠀⠄⠀⢀
⠐⢄⠀⠄⠀⠄⠐⠀⠀⠁⢀⠀⠅⠀⠄⠄⠀⠀⠀⢀⠔⠕⠄⠄⠑⠀⠀⠁⠀⠐⠔⢄⠀⠀⢄⠐⠔⢀⠁⢐⢀⠐⠄⠐⠁⠀⠄⠐⠐⠄⠁⠀⠐⠀⠄⠀⠑⠄⠐⠀⠀⠐⠀⠔⠀⠁⠔⠀⠁⠀⠀⠑⠄⠔⠀⠀⠀⠑⠐⠀
⠀⠀⢀⠄⠐⠀⠀⠀⢀⠄⠀⢑⢀⠁⠐⢀⠑⠀⠔⠐⢁⢐⠀⠐⢀⠀⠑⢐⠀⠀⢀⠐⢐⢔⠐⠄⢀⠁⠁⢐⠑⢄⢄⠑⠀⠁⠐⠐⢁⠐⠑⢁⠑⢀⢀⢀⠐⠁⢐⢐⠀⠐⠐⠀⢀⠑⢁⠁⠀⠀⠀⠑⠀⠁⢐⢀⠑⠀⢀⢀
⠁⢀⠀⠀⢁⠀⠀⠅⠀⠀⠅⠀⠀⠐⢀⢀⢀⠄⠀⠅⠀⢁⠔⠀⠁⢁⠁⠁⠑⢄⠀⠁⠁⢀⢀⠄⠑⢔⠀⠐⠔⠁⠀⠄⠀⠑⢀⠀⠕⠄⠀⠀⠄⢀⠀⠁⢄⠁⢄⠄⠐⠄⢄⠔⠀⠀⠐⠁⢀⠐⠀⠀⠅⠀⠀⠔⠀⢀⠁⠀
⠀⢄⠐⠁⠀⠐⠕⠀⠄⠐⠀⠐⠀⢀⠐⠐⠀⠀⠅⠀⠄⠁⢀⠄⠀⠄⠔⠑⢀⠀⠅⠀⠅⠄⠀⠄⠁⢀⠄⠀⢀⠀⢁⢀⠕⠀⠀⠑⠀⠐⠀⢄⠐⠁⢄⠄⠁⠐⠄⠐⢀⠀⠁⠄⠔⠀⢄⠀⠁⠄⠔⠁⢐⠄⠐⠀⠀⠑⢀⠔
⢀⠐⢀⠀⠀⠐⠄⠁⠐⠄⠐⠀⢀⠑⠁⠄⠀⠁⠐⠀⢀⠀⠁⢀⠀⠐⠐⠔⠁⢀⠀⠑⠀⠀⠐⠀⢔⠑⠀⢐⠀⢁⢀⠐⠀⢀⠐⢀⠄⠁⢄⠁⠀⠀⠁⠀⠀⠀⢐⢀⢁⢑⠀⢀⠑⠐⠁⠀⢀⢀⠀⠁⢀⢀⠀⠀⠐⢀⠀⠐
⢀⢁⠀⠀⢑⢅⢁⢄⢀⢀⠅⠀⠀⠄⢀⢁⢐⢁⢀⢅⢄⠀⠀⢀⢀⠐⠅⠁⠀⠀⢁⠐⠀⢀⠀⠀⠐⢀⠀⢀⠄⠅⠐⢐⠀⠀⠔⠁⠑⠐⠄⠀⠄⠀⠅⠁⠄⠐⠀⠀⠁⠁⠀⠄⠅⠀⠀⠄⠄⠅⠀⠄⠀⠄⠀⠁⠀⠀⠔⠀
⠁⠀⠀⠁⠀⠀⠀⢀⠄⠀⠀⠀⠀⠄⠄⠀⢀⠀⠐⢀⠀⠀⢄⠔⠄⠀⠄⠀⠀⠔⠕⢀⠔⠀⠀⠄⠄⠀⠁⠐⠀⠀⠕⢀⠕⠁⠀⠁⢑⠀⠀⢀⢀⠐⠄⠀⠑⠀⠀⠁⢄⠔⠑⢐⠀⠑⢄⠐⠀⠀⠐⠀⠀⠀⠀⠀⠄⠁⢀⠄
⠀⠁⠐⠀⠁⠀⠄⠀⠑⠀⠀⢀⠀⠐⠀⠄⠀⠑⠀⠀⢐⠀⠁⢅⠀⠀⠀⠐⠀⢀⠄⠀⢁⢄⠀⠁⠔⠑⠄⠀⠑⢄⠔⠁⢀⠀⠀⢄⠄⠀⠀⠐⠁⠁⢀⠐⠄⠀⠁⠐⠁⢀⢑⠁⠐⠐⢀⠑⠔⠀⠁⠀⢁⢀⠄⠁⢐⠀⠀⠀
⠀⠅⠁⢀⠐⠀⠁⠐⠀⠁⠐⢄⠀⢄⢀⠀⠄⢀⠁⢁⠄⠀⠐⠀⢑⠄⠀⠑⠐⠀⠁⠀⠁⠐⠐⠀⠁⠄⠄⢀⠄⠁⠐⢀⠄⠐⠀⠄⠀⠄⠀⠀⢀⠄⢀⢐⠀⠑⠀⠀⠄⢄⢄⠀⢅⠀⠀⠄⠀⠅⠀⠄⠐⢀⠀⠔⠅⠀⠄⢁
⠄⠀⠄⠄⠀⠄⠀⢀⠀⠐⠀⠀⠁⠀⠔⠄⠀⠀⠁⠀⠄⢄⠀⠐⠀⠀⠄⢑⠀⠁⠅⠀⠁⠀⢀⠄⠑⢀⠄⢀⢀⠔⢀⠀⠑⠄⠀⠅⠀⠀⠅⢕⠀⠐⢐⠀⠄⠕⠀⠀⢀⠀⠀⢀⠀⠁⠀⠀⠐⢀⠐⠁⢀⠔⠁⢐⠀⠀⠐⠀
⠀⠐⢁⢀⠐⠀⢀⠁⠀⠀⠁⠑⠄⠀⢁⠐⠁⠅⢀⠐⢀⠄⠀⠀⠐⠀⠅⢀⠐⢀⢀⠁⠅⢀⠀⠄⠔⠑⠁⠀⠁⠀⠐⠁⢀⠀⠀⢀⠀⠐⠄⠔⠐⠁⢄⠀⠅⢄⠑⠀⢀⠐⠀⠀⢁⢀⠀⢀⠁⢀⠁⠅⠁⠀⠁⠀⠀⠄⠀⠁
⠀⠀⢀⠀⠄⢁⠀⠀⠄⠀⢁⢁⠀⠀⠀⠐⠀⠄⠀⠐⠀⢀⢀⠁⠁⠄⠄⢀⠀⠀⠑⢀⠀⠑⠐⠁⠀⠀⠁⢐⠄⠀⢀⠐⠄⠐⢀⠁⠑⢀⠀⠀⠐⠀⢑⠄⠀⠁⠀⠅⠐⠄⠀⠀⠄⠀⠄⠁⠀⠄⢁⢀⠁⠁⠄⠀⠀⠀⠀⢄
⠑⠀⠀⠀⢀⠀⠁⠄⠐⠀⠀⠄⢄⠀⠐⠐⠀⠑⢁⠀⠔⠀⠀⠀⠀⠀⠕⢄⠀⠐⠀⢀⠔⠅⢀⠀⠐⠀⠅⢐⠀⠕⠐⢀⠀⠔⠀⠅⠀⠀⠀⠄⢀⠁⢀⠀⠀⠔⠀⠐⠁⢀⠀⠁⢀⠁⠀⠐⠐⠄⠐⠐⠄⠀⠀⠀⠀⠀⠔⠐
⠐⠀⢐⠀⠀⠀⢀⠀⠐⠐⠀⠀⠐⠀⠄⢀⠁⢄⠀⠑⢀⠀⠐⢀⢄⠀⠀⢀⠀⢅⢔⠁⠄⠐⠀⠁⠀⠑⠀⠀⠐⠁⠄⠀⢁⢀⠀⠁⠐⠁⠀⠀⠀⠀⠀⠀⠀⠀⠐⢀⠄⠀⢀⢔⠑⢅⠀⠐⢄⠁⢀⠄⢁⢀⠐⠀⠀⢀⢀⢑
⠀⠄⠅⢀⠁⠀⠀⠅⠁⠀⢄⠀⠁⠐⠁⢀⠀⠀⠀⠀⠀⠑⠀⠄⢀⠀⠀⢀⠐⠀⠀⢀⠁⠐⢀⠄⠁⢔⠄⠀⠄⠄⠑⠄⠁⠀⠀⠁⠐⠐⠄⠁⢄⠀⢀⠄⠁⠀⠔⠁⢀⠐⠄⠀⠀⠀⢁⢐⠀⠀⠄⠀⠀⢀⠀⠅⠀⠀⠀⠀
⠔⠀⠄⠀⢀⠄⠁⢀⠁⠄⠀⠀⠑⠀⠐⠁⠀⠐⠑⢀⠄⠄⠀⠀⢄⠀⠔⠔⢀⠀⠁⠀⠔⠀⢀⠄⠀⠀⠁⢐⠀⠑⠀⠀⠀⢅⠀⠀⢀⠀⠁⠄⠀⠁⢀⠀⠔⠐⠀⠀⢅⠀⠐⢀⠀⠀⠄⢀⠐⠔⠀⠁⠄⠀⠁⠀⠔⠐⠀⠀
⠀⠐⢀⠐⠀⠁⢀⠀⠀⠐⠐⢀⢄⠐⢄⠐⠀⠅⠀⠁⠁⠄⠐⢁⠄⠀⠀⢄⠀⠅⠔⠀⢁⠀⠐⠄⢀⠀⠁⠀⠐⠀⢀⠑⢀⠄⠀⠅⠀⠀⠅⠀⠀⢀⢔⠐⠄⠀⠁⠀⠐⠀⠀⢀⠑⠀⠄⠐⢁⢀⠀⢄⢄⠁⢀⠀⢐⠐⠁⠁
⠁⠄⠄⠀⠀⠁⠀⢐⠀⠐⠀⠄⢑⠀⠀⠑⠄⠁⢁⢀⠀⢑⠔⠁⠀⠄⠄⠀⢀⠀⠑⠔⠁⢁⠀⠄⢁⠔⠀⢀⠔⠀⢐⠀⠀⠀⠄⠄⠀⠐⠁⢁⠔⠁⠐⠐⠁⢀⢀⠀⠁⠔⠀⠀⠀⠅⠁⠀⠄⠀⠔⠁⢑⠀⠀⠀⠀⠀⠐⠀
⠁⠀⠅⠐⠀⠁⠀⠀⠐⠁⠀⠀⠕⠀⠀⠅⠀⠐⠀⠀⠕⠁⠀⠄⠅⠀⠀⠐⠀⠐⠅⠀⠀⠄⠀⠀⠀⠀⠀⠐⠀⠀⠀⠀⠁⠀⠀⠀⠄⠀⠐⠁⠀⠄⠁⠀⠁⠄⠀⠐⠄⠀⠅⠀⠀⠔⠁⠀⠀⠕⠀⠀⠀⠀⠀⠁⠀⠁⠀⠀
</pre>
 
Line 2,134 ⟶ 4,856:
This then allows the REXX program to compress two rows of the Ulam spiral into one by processing two rows at a time by comparing each character to the character on the next line &nbsp; (when comparing two lines as a pair):
::* if a char on row &nbsp; '''k''' &nbsp; is a block, and the char on row &nbsp; '''k+1''' &nbsp; is a block, then a &nbsp; "block" &nbsp; is used.
::* if a char on row &nbsp; '''k''' &nbsp; is a block, and the char on row &nbsp; '''k+1''' &nbsp; is a blank, then a &nbsp; "uhblkUHblk" &nbsp; is used.
::* if a char on row &nbsp; '''k''' &nbsp; is a blank, and the char on row &nbsp; '''k+1''' &nbsp; is a block, then a &nbsp; "lhblkLHblk" &nbsp; is used.
::* if a char on row &nbsp; '''k''' &nbsp; is a blank, and the char on row &nbsp; '''k+1''' &nbsp; is a blank, then a &nbsp; &nbsp; blank &nbsp; is used.
 
For codepage 437:
::::::* &nbsp; a "block" is 'db'x &nbsp; &nbsp; █ &nbsp; &nbsp; &nbsp; (a full block)
 
::::::* &nbsp; a "uhblkLHblk" is 'dfdc'x &nbsp; &nbsp; ▄ &nbsp; &nbsp; &nbsp; (a '''L'''ower '''H'''alf '''bl'''oc'''k''')
 
::::::* &nbsp; a "UHblk" is 'df'x &nbsp; &nbsp; ▀ &nbsp; &nbsp; &nbsp; (a '''U'''pper '''H'''alf '''bl'''oc'''k''')
 
::::::* a "lhblk" is 'dc'x &nbsp; &nbsp; ▀
Or, to show all three characters in the (above) ordered next to each other (separated by a blank): &nbsp; █ ▄ ▀
 
This allows the displaying of the Ulam prime spiral to keep a (mostly) square aspect ratio.
 
The characters chosen allow for the HTML on Rosetta Code to shrink (via STYLE ''font-size'') the displayed output to half their normal height.
===counter-clockwise===
<langsyntaxhighlight lang="rexx">/*REXX pgmprogram shows cntr-clockwisecounter─clockwise Ulam spiral of primes shown in a square matrix.*/
parse arg size init char . /*get theobtain matrixoptional sizearguments from the CL*/
if size=='' | size=='",'" then size= 79 /*NoNot sizespecified? Then use defaultthe of 79default.*/
if init=='' | init=='",'" then init= 1 /*No init?" Then use default of 1 " " " " " */
if char=='' then char=' "'" /*No char?" Then use default of " " " " " */
tot=size**2; offset=init-1 /*the total number of numbers in spiral; start offset*/
uR.=0; bR.=0 /*define the upper/bottom right corners.*/
uR.=0; bR.=0; do od=1 by 2 to tot; _=od**2+1+offset; uR._=1; _=_ + od; bR._=1; end /*od*/
bL.=0; uL.=0 /*define the bottom/upper left corners. */
bL.=0; uL.=0; do ev=2 by 2 to tot; _=ev**2+1+offset; bL._=1; _=_ + ev; uL._=1; end /*ev*/
$.=
bigP=0; #p=0; app=1; inc=0; r=1; $=0; minR=1; maxR=1; $=0; !.=
/*──────────────────────────────────────────────construct the spiral #s.*/
do i=init for tot; r=r+inc; minR=min(minR,r); maxR=max(maxR,r)
x=isPrime(i); if x then bigP=max(bigP,i); #p=#p+x /*bigP, #primes.*/
if app then $.r=$.r || x /*append token.*/
else $.r= x || $.r /*prepend token.*/
if uR.i then do; app=1; inc=+1; iterate; end /*advance ↓ */
if bL.i then do; app=0; inc=-1; iterate; end /* " ↑ */
if bR.i then do; app=0; inc= 0; iterate; end /* " ► */
if uL.i then do; app=1; inc= 0; iterate; end /* " ◄ */
end /*i*/
 
app=1; do j bigP=minR0; to maxR #p=0; by 2 inc=0; jp minR=j+1; $maxR=$+1; r=1; $=0; /*fold two lines*/ $.=; !.=
/*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ construct the spiral #s.*/
do k=1 for length($.j); top=substr($.j,k,1) /*the 1st line*/
do i=init for tot; r= r + inc; minR= min(minR, r); maxR= bot=wordmax(substr($.jpmaxR,k,1) 0,1r) /*2nd line*/
x= isPrime(i); if top then if botx then !.$bigP=!.$'█' max(bigP, i); #p= #p + x /*has top &/*bigP, bot#primes.*/
if app then $.r= $.r || x else !.$=!.$'▀' /*hasappend top,¬ bottoken.*/
else if$.r= bot x then !.|| $=!.$'▄'r /*¬ top, has bot /*prepend token.*/
if uR.i then do; app= 1; inc= +1; iterate /*i*/; else !.$=!.$' ' end /*¬advance top, ¬ bot.*/
if bL.i then do; app= 0; inc= -1; iterate /*i*/; end /* " ↑ */
end /*k*/
if endbR.i then do; /*j*/ app= 0; inc= 0; iterate /*i*/; end /* [↓] show" ► prime# spiral matrix*/
if uL.i then do; app= 1; inc= 0; iterate /*i*/; end /* " do m=1 for $; say !.m; end /*m*/
end /*i*/ /* [↓] pack two */
/*lines ──► one.*/
do j=minR to maxR by 2; jp= j + 1; $= $ + 1 /*fold two lines*/
do k=1 for length($.j); top= substr($.j, k, 1) /*the 1st line.*/
bot= word( substr($.jp, k, 1) 0, 1) /*the 2nd line.*/
if top then if bot then !.$= !.$'█' /*has top & bot.*/
else !.$= !.$'▀' /*has top,¬ bot.*/
else if bot then !.$= !.$'▄' /*¬ top, has bot*/
else !.$= !.$' ' /*¬ top, ¬ bot*/
end /*k*/
end /*j*/ /* [↓] show the prime spiral matrix.*/
do m=1 for $; say !.m; end /*m*/
say; say init 'is the starting point,' ,
tot 'numbers used,' #p "primes found, largest prime:" bigP
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*───────────────────────────────────ISPRIME subroutine──────────────────────────────*/
isPrime: procedure; parse arg x; if wordpos(x<, '2 3 5 7 11 13 17 19') \==0 then return 01
if wordpos(x,'2<17 3 5then return 7')\==0; if x// 2 ==0 then return 10
if x//2==0 then return 0; if x// 3==0 ==0 then return 0
do j=5 by 6 until j /*j>x;get ifthe xlast digit*//j==0 then return 0 parse var x '' -1 _; if x//(j+2) _==05 then return 0; end
if x// 7 ==0 then return 0
return 1</lang>
if x//11 ==0 then return 0
{{out}} when the default inputs are used:
if x//13 ==0 then return 0
<pre>
 
do j=17 by 6 until j*j > x; if x//j ==0 then return 0
if x//(j+2) ==0 then return 0
end /*j*/; return 1</syntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
 
(Shown at three-quarter size.)
<pre style="font-size:75%">
▀ ▀ ▀ ▄ ▀ ▄ ▄▀ ▄▀ ▀ ▀ ▄ ▄ ▀ ▄▀
▄▀ ▀▄ ▄ ▄ ▀ ▄▀ ▀ ▄▀ ▀ ▀ ▀ ▀ ▄ ▀ ▄
Line 2,238 ⟶ 4,969:
1 is the starting point, 6241 numbers used, 811 primes found, largest prime: 6229
</pre>
{{out}}|output|text=&nbsp; when the following input is used: &nbsp; &nbsp; <tt> , &nbsp; 41 </tt>}}
 
<pre>
(Shown at three-quarter size.)
<pre style="font-size:75%">
▀▄ ▄▀ ▄ ▀ ▄ ▀▄▀ ▄ ▀ ▀ ▀ ▄ ▀ ▄ ▄▀
▀ ▀ ▀▄ ▄ ▀ ▄▀ ▀ ▀▄ ▄ ▄ ▀ ▄▀
Line 2,283 ⟶ 5,016:
41 is the starting point, 6241 numbers used, 805 primes found, largest prime: 6277
</pre>
{{out|output|text=&nbsp; with an input of &nbsp; '''416''' &nbsp; can be viewed here at &nbsp; ───► &nbsp; [[Ulam spiral (for primes)/REXX‎]]}}
 
{{out}} with an input of '''416''' can be viewed here at &nbsp; ───► &nbsp; [[Ulam spiral (for primes)/REXX‎]]
<br>
 
===clockwise===
This REXX version is presented here to show the difference between a clockwise and a counter-clockwise Ulam (prime) spiral.
<langsyntaxhighlight lang="rexx">/*REXX pgmprogram shows a clockwise Ulam spiral of primes shown in a square matrix. */
parse arg size init char . /*get theobtain matrixoptional sizearguments from the CL*/
if size=='' | size=='",'" then size= 79 /*NoNot sizespecified? Then use defaultthe of 79default.*/
if init=='' | init=='",'" then init= 1 /*No init?" Then use default of 1 " " " " " */
if char=='' then char=' "'" /*No char?" Then use default of " " " " " */
tot=size**2; offset=init-1 /*the total number of numbers in spiral; start offset*/
uR.=0; bR.=0 /*define the upper/bottom right corners.*/
uR.=0; bR.=0; do od=1 by 2 to tot; _=od**2+1+offsetinit; uR._=1; _=_ + od; bR._=1; end /*od*/
bL.=0; uL.=0 /*define the bottom/upper left corners. */
bL.=0; uL.=0; do ev=2 by 2 to tot; _=ev**2+1+offsetinit; bL._=1; _=_ + ev; uL._=1; end /*ev*/
$.=
bigP=0; #p=0; app=1; inc=0; r=1; $=0; minR=1; maxR=1; $=0; !.=
/*──────────────────────────────────────────────construct the spiral #s.*/
do i=init for tot; r=r+inc; minR=min(minR,r); maxR=max(maxR,r)
x=isPrime(i); if x then bigP=max(bigP,i); #p=#p+x /*bigP, #primes.*/
if app then $.r=$.r || x /*append token.*/
else $.r= x || $.r /*prepend token.*/
if uR.i then do; app=1; inc=+1; iterate; end /*advance ↓ */
if bL.i then do; app=0; inc=-1; iterate; end /* " ↑ */
if bR.i then do; app=0; inc= 0; iterate; end /* " ► */
if uL.i then do; app=1; inc= 0; iterate; end /* " ◄ */
end /*i*/
 
app=1; do j bigP=minR0; to maxR #p=0; by 2 inc=0; jp minR=j+1; $maxR=$+1; r=1; $=0; /*fold two lines*/ $.=; !.=
/*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ construct the spiral #s.*/
do k=1 for length($.j); top=substr($.j,k,1) /*the 1st line*/
do i=init for tot; r= r + inc; minR= min(minR, r); maxR= bot=wordmax(substr($.jpmaxR,k,1) 0,1r) /*2nd line*/
x= isPrime(i); if top then if botx then !.$bigP=!.$'█' max(bigP, i); #p= #p + x /*has top &/*bigP, bot#primes.*/
if app then $.r= $.r || x else !.$=!.$'▀' /*hasappend top,¬ bottoken.*/
else if$.r= bot x then !.|| $=!.$'▄'r /*¬ top, has bot /*prepend token.*/
if uR.i then do; app= 1; inc= +1; iterate /*i*/; else !.$=!.$' ' end /*¬advance top, ¬ bot*/
if bL.i then do; app= 0; inc= -1; iterate /*i*/; end /* " ↑ */
end /*k*/
if endbR.i then do; /*j*/app= 0; inc= 0; iterate /*i*/; end /* [↓] show" ► prime# spiral matrix*/
if uL.i then do; app= 1; inc= 0; iterate /*i*/; end /* " do m=1 for $; say !.m; end /*m*/
end /*i*/ /* [↓] pack two */
/*lines ──► one.*/
do j=minR to maxR by 2; jp= j + 1; $= $ + 1 /*fold two lines*/
do k=1 for length($.j); top= substr($.j, k, 1) /*the 1st line.*/
bot= word( substr($.jp, k, 1) 0, 1) /*the 2nd line.*/
if top then if bot then !.$= !.$'█' /*has top & bot.*/
else !.$= !.$'▀' /*has top,¬ bot.*/
else if bot then !.$= !.$'▄' /*¬ top, has bot*/
else !.$= !.$' ' /*¬ top, ¬ bot*/
end /*k*/
end /*j*/ /* [↓] show the prime spiral matrix.*/
do m=1 for $; say !.m; end /*m*/
say; say init 'is the starting point,' ,
tot 'numbers used,' #p "primes found, largest prime:" bigP
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*───────────────────────────────────ISPRIME subroutine──────────────────────────────*/
isPrime: procedure; parse arg x; if wordpos(x<, '2 3 5 7 11 13 17 19') \==0 then return 01
if wordpos(x,'2<17 3 5then return 7')\==0; if x// 2 ==0 then return 10
if x//2==0 then return 0; if x// 3==0 ==0 then return 0
do j=5 by 6 until j /*j>x;get ifthe xlast digit*//j==0 then return 0 parse var x '' -1 _; if x//(j+2) _==05 then return 0; end
if x// 7 ==0 then return 0
return 1</lang>
if x//11 ==0 then return 0
{{out}} when using the default input:
if x//13 ==0 then return 0
<pre>
 
do j=17 by 6 until j*j > x; if x//j ==0 then return 0
if x//(j+2) ==0 then return 0
end /*j*/; return 1</syntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
 
(Shown at three-quarter size.)
<pre style="font-size:75%">
▀ ▄ ▄▀ ▄ ▄ ▄ ▄ ▀ ▀ ▀ ▄ ▀ ▄ ▀ ▀ ▀ ▄ ▄
▄ ▄▀ ▀ ▄▀ ▀▄ ▄ ▀ ▀▄ ▄ ▄ ▄ ▀
Line 2,376 ⟶ 5,115:
1 is the starting point, 6241 numbers used, 811 primes found, largest prime: 6229
</pre>
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
# Project : Ulam spiral (for primes)
load "guilib.ring"
load "stdlib.ring"
 
paint = null
 
new qapp
{
win1 = new qwidget() {
setwindowtitle("Ulam spiral")
setgeometry(100,100,560,600)
label1 = new qlabel(win1) {
setgeometry(10,10,800,600)
settext("")
}
new qpushbutton(win1) {
setgeometry(220,500,100,30)
settext("draw")
setclickevent("draw()")
}
show()
}
exec()
}
 
func draw
p1 = new qpicture()
color = new qcolor() {
setrgb(0,0,255,255)
}
pen = new qpen() {
setcolor(color)
setwidth(1)
}
paint = new qpainter() {
begin(p1)
setpen(pen)
 
usn = 81
ulamspiral(usn)
 
endpaint()
}
label1 { setpicture(p1) show() }
return
 
func ulamspiral(nr)
button = list(nr)
win1{
sizenew = sqrt(nr)
for n = 1 to nr
col = n%9
if col = 0 col = 9 ok
row = ceil(n/9)
 
button[n] = new qpushbutton(win1)
{
setgeometry(60+col*40,60+row*40,40,40)
setclickevent("movetile(" + string(n) +")")
show()
}
next
n = 9
result = newlist(n,n)
k = 1
top = 1
bottom = n
left = 1
right = n
while (k<=n*n)
for i=left to right
result[top][i]=k
k = k + 1
next
top = top + 1
for i=top to bottom
result[i][right]=k
k = k + 1
next
right = right - 1
for i=right to left step -1
result[bottom][i]=k
k = k + 1
next
bottom = bottom - 1
for i=bottom to top step -1
result[i][left] = k
k = k + 1
next
left = left + 1
end
for m = 1 to n
for p = 1 to n
pos = (m-1)*n + p
if isprime(result[m][p])
button[pos] {settext(string(result[m][p]))}
ok
next
next
}
</syntaxhighlight>
Outputimage:
 
[https://www.dropbox.com/s/doqvdr8l852t8o9/CalmoSoftUlamSpiral.jpg?dl=0 Ulam spiral]
 
=={{header|Ruby}}==
It finds the number from the position ( the coordinates ).
{{trans|Python}}
<langsyntaxhighlight lang="ruby">require 'prime'
 
def cell(n, x, y, start=1)
Line 2,407 ⟶ 5,254:
show_spiral(9)
show_spiral(25)
show_spiral(25, "# ")</langsyntaxhighlight>
 
{{out}}
Line 2,479 ⟶ 5,326:
===Another Version===
computes the next spiral position.
<langsyntaxhighlight lang="ruby">require 'prime'
 
def spiral_generator(x=0, y=0)
Line 2,514 ⟶ 5,361:
puts "\nN : #{n}"
ulam_spiral(n)
end</langsyntaxhighlight>
 
{{out}}
Line 2,591 ⟶ 5,438:
The method of presentation of the result consulted " REXX ".
 
=={{header|ScalaRust}}==
{{trans|Kotlin}}
{{works with|Rust|1.11.0}}
<lang scala>object Ulam extends App {
<syntaxhighlight lang="rust">use std::fmt;
val u = generate(9)
for (row <- u) println("[" + row.toList.mkString.replaceAll(",", "") + ']')
println()
final val c = '*'
for (row <- u)
println(("[" + row.toList.mkString + ']').replaceAll("\\[\\s+\\d+", s"[ $c ").replaceAll("\\s+\\d+", s" $c ").replaceAll(",", ""))
 
enum Direction { RIGHT, UP, LEFT, DOWN }
private object Direction extends Enumeration {
use ulam::Direction::*;
val RIGHT, UP, LEFT, DOWN = Value
 
/// Indicates whether an integer is a prime number or not.
fn is_prime(a: u32) -> bool {
match a {
2 => true,
x if x <= 1 || x % 2 == 0 => false,
_ => {
let max = f64::sqrt(a as f64) as u32;
let mut x = 3;
while x <= max {
if a % x == 0 { return false; }
x += 2;
}
true
}
}
}
 
pub struct Ulam { u : Vec<Vec<String>> }
 
impl Ulam {
/// Generates one `Ulam` object.
pub fn new(n: u32, s: u32, c: char) -> Ulam {
let mut spiral = vec![vec![String::new(); n as usize]; n as usize];
let mut dir = RIGHT;
let mut y = (n / 2) as usize;
let mut x = if n % 2 == 0 { y - 1 } else { y }; // shift left for even n's
for j in s..n * n + s {
spiral[y][x] = if is_prime(j) {
if c == '\0' { format!("{:4}", j) } else { format!(" {} ", c) }
}
else { String::from(" ---") };
 
match dir {
RIGHT => if x as u32 <= n - 1 && spiral[y - 1][x].is_empty() && j > s { dir = UP; },
UP => if spiral[y][x - 1].is_empty() { dir = LEFT; },
LEFT => if x == 0 || spiral[y + 1][x].is_empty() { dir = DOWN; },
DOWN => if spiral[y][x + 1].is_empty() { dir = RIGHT; }
};
 
match dir { RIGHT => x += 1, UP => y -= 1, LEFT => x -= 1, DOWN => y += 1 };
}
Ulam { u: spiral }
}
}
 
impl fmt::Display for Ulam {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for row in &self.u {
writeln!(f, "{}", format!("{:?}", row).replace("\"", "").replace(", ", ""));
};
writeln!(f, "")
}
}</syntaxhighlight>
main.rs :
<syntaxhighlight lang="rust">mod ulam;
use ulam::*;
 
// Program entry point.
fn main() {
print!("{}", Ulam::new(9, 1, '\0'));
print!("{}", Ulam::new(9, 1, '*'));
}</syntaxhighlight>
{{out}}
<pre>[ --- --- --- --- 61 --- 59 --- ---]
[ --- 37 --- --- --- --- --- 31 ---]
[ 67 --- 17 --- --- --- 13 --- ---]
[ --- --- --- 5 --- 3 --- 29 ---]
[ --- --- 19 --- --- 2 11 --- 53]
[ --- 41 --- 7 --- --- --- --- ---]
[ 71 --- --- --- 23 --- --- --- ---]
[ --- 43 --- --- --- 47 --- --- ---]
[ 73 --- --- --- --- --- 79 --- ---]
 
[ --- --- --- --- * --- * --- ---]
[ --- * --- --- --- --- --- * ---]
[ * --- * --- --- --- * --- ---]
[ --- --- --- * --- * --- * ---]
[ --- --- * --- --- * * --- * ]
[ --- * --- * --- --- --- --- ---]
[ * --- --- --- * --- --- --- ---]
[ --- * --- --- --- * --- --- ---]
[ * --- --- --- --- --- * --- ---]</pre>
 
=={{header|Scala}}==
{{trans|Kotlin}}
<syntaxhighlight lang="scala">object Ulam extends App {
generate(9)()
generate(9)('*')
 
private object Direction extends Enumeration { val RIGHT, UP, LEFT, DOWN = Value }
 
private def generate(n: Int, si: Int = 1)(c: Char = 0) {
assert(n > 1, "n > 1")
val spirals = new Array[Array[String]](n).transform {_ => new Array[String](n) }
for (i <- spiral.indices) spiral(i) = new Array[String](n)
 
import Direction._
Line 2,614 ⟶ 5,545:
var y = n / 2
var x = if (n % 2 == 0) y - 1 else y // shift left for even n's
for (j <- si to n * n - 1 + si) {
spirals(y)(x) = if (isPrime(j)) if (c == 0) "%4d".format(j) else s" $c " else " ---"
 
dir match {
case RIGHT => if (x <= n - 1 && spirals(y - 1)(x) == null && j > si) dir = UP
case UP => if (spirals(y)(x - 1) == null) dir = LEFT
case LEFT => if (x == 0 || spirals(y + 1)(x) == null) dir = DOWN
case DOWN => if (spirals(y)(x + 1) == null) dir = RIGHT
}
 
Line 2,631 ⟶ 5,562:
}
}
println("[" + s.map(_.mkString("")).reduceLeft(_ + "]\n[" + _) + "]\n")
spiral
}
 
Line 2,642 ⟶ 5,573:
true
}
}</langsyntaxhighlight>
 
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">require('Imager');
 
require('ntheory');
var (n=512, start=1, file='ulam.png')
 
var (n=512, start=1, file='ulam.png') = ARGV»to_i»()...;
 
ARGV.getopt(
'n=i' => \n,
's=i' => \start,
'f=s' => \file,
)
 
func cell(n, x, y, start) {
y -= (n >> 1);
x -= (n-1 >> 1);
var l = 2*(x.abs > y.abs  ? x.abs  : y.abs);
var d = (y > x ? (l*3 + x + y)  : (l - x - y));
(l-1)**2 + d + start - 1;
}
 
 
var black = %s'O<Imager::Color'>.new('#000000');
var white = %s'O<Imager::Color'>.new('#FFFFFF');
 
 
var img = %s'O<Imager'>.new(xsize => n, ysize => n, channels => 1);
img.box(filled => 1, color => white);
 
 
for y=(^n), x=(^n) {
n.range.each { |y|
if (cell(n, x, y, start).is_prime) {
n.range.each { |x|
var vimg.setpixel(x = cell(n,> x, y => y, startcolor => black);
%S'ntheory'.is_prime(v) && (
img.setpixel(x => x, y => y, color => black)
);
}
}
 
 
img.write(file => file);</langsyntaxhighlight>
Output image: [https://github.com/trizen/rc/blob/master/img/ulam-spiral-sidef.png Ulam spiral]
 
=={{header|Tcl}}==
Line 2,680 ⟶ 5,614:
This uses a coroutine to walk around the circle, laying glyphs every prime number of tiles. Some more elaborate, interactive Tk GUIs for playing with Ulam spirals are at [http://wiki.tcl.tk/11363 Ulam Spiral] and [http://wiki.tcl.tk/23052 Ulam Spiral Demo] on the Tcl'ers Wiki.
 
<langsyntaxhighlight Tcllang="tcl">proc is_prime {n} {
if {$n == 1} {return 0}
if {$n in {2 3 5}} {return 1}
Line 2,730 ⟶ 5,664:
}
 
puts [join [lmap row $cells {join $row " "}] \n]</langsyntaxhighlight>
 
The mark used is Unicode's OGHAM FEATHER MARK .. the closest I could find to a Tcl logo.
Line 2,769 ⟶ 5,703:
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
Function build_spiral(n)
'declare a two dimentional array
Line 2,850 ⟶ 5,784:
'test with 9
build_spiral(9)
</syntaxhighlight>
</lang>
 
{{Out}}
Line 2,864 ⟶ 5,798:
73 -- -- -- -- -- 79 -- --
</pre>
 
=={{header|Wren}}==
{{trans|Kotlin}}
{{libheader|Wren-dynamic}}
{{libheader|Wren-math}}
{{libheader|Wren-str}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang="wren">import "./dynamic" for Enum
import "./math" for Int
import "./str" for Char
import "./fmt" for Fmt
 
var Direction = Enum.create("Direction", ["right", "up", "left", "down"])
 
class Ulam {
static generate(n, i, c) {
if (n <= 1) Fiber.abort ("'n' must be more than 1.")
var s = List.filled(n, null)
for (i in 0...n) s[i] = List.filled(n, "")
var dir = Direction.right
var y = (n/2).floor
var x = (n % 2 == 0) ? y - 1 : y // shift left for even n's
for (j in i..n * n - 1 + i) {
s[y][x] = Int.isPrime(j) ? (Char.isDigit(c) ? Fmt.d(4, j) : " %(c) ") : " ---"
if (dir == Direction.right) {
if (x <= n - 1 && s[y - 1][x] == "" && j > i) dir = Direction.up
} else if (dir == Direction.up) {
if (s[y][x - 1] == "") dir = Direction.left
} else if (dir == Direction.left) {
if (x == 0 || s[y + 1][x] == "") dir = Direction.down
} else if (dir == Direction.down) {
if (s[y][x + 1] == "") dir = Direction.right
}
 
if (dir == Direction.right) {
x = x + 1
} else if (dir == Direction.up) {
y = y - 1
} else if (dir == Direction.left) {
x = x - 1
} else if (dir == Direction.down) {
y = y + 1
}
}
 
for (row in s) Fmt.print("$s", row)
System.print()
}
}
 
Ulam.generate(9, 1, "0") // with digits
Ulam.generate(9, 1, "*") // with *</syntaxhighlight>
 
{{out}}
<pre>
--- --- --- --- 61 --- 59 --- ---
--- 37 --- --- --- --- --- 31 ---
67 --- 17 --- --- --- 13 --- ---
--- --- --- 5 --- 3 --- 29 ---
--- --- 19 --- --- 2 11 --- 53
--- 41 --- 7 --- --- --- --- ---
71 --- --- --- 23 --- --- --- ---
--- 43 --- --- --- 47 --- --- ---
73 --- --- --- --- --- 79 --- ---
 
--- --- --- --- * --- * --- ---
--- * --- --- --- --- --- * ---
* --- * --- --- --- * --- ---
--- --- --- * --- * --- * ---
--- --- * --- --- * * --- *
--- * --- * --- --- --- --- ---
* --- --- --- * --- --- --- ---
--- * --- --- --- * --- --- ---
* --- --- --- --- --- * --- ---
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">func IsPrime(N); \Return 'true' if N is prime
int N, I;
[if N <= 2 then return N = 2;
if (N&1) = 0 then \even >2\ return false;
for I:= 3 to sqrt(N) do
[if rem(N/I) = 0 then return false;
I:= I+1;
];
return true;
];
 
int N, X, Y, Len, Dir, DX, DY, Side, Step;
[SetVid($13);
X:= 320/2; Y:= 200/2;
N:= 1;
Len:= 1;
Dir:= 0; \Rt, Up, Lt, Dn
DX:= [1, 0, -1, 0];
DY:= [0, -1, 0, 1];
repeat for Side:= 1 to 2 do
[for Step:= 1 to Len do
[if IsPrime(N) then Point(X, Y, $F);
N:= N+1;
X:= X + DX(Dir); \move in current direction
Y:= Y + DY(Dir);
];
Dir:= (Dir+1) & 3; \set next direction
];
Len:= Len+1;
until Y = 0; \reached top
]</syntaxhighlight>
 
=={{header|Yabasic}}==
{{trans|Phix}}
<syntaxhighlight lang="yabasic">sub is_prime(n)
local p
for p=2 to n
if p*p>n break
if mod(n,p)=0 return false
next
return n>=2
end sub
sub spiral(w, h, x, y)
if y then
return w+spiral(h-1,w,y-1,w-x-1)
else
return x
end if
end sub
w = 9 : h = 9
for i=h-1 to 0 step -1
for j=w-1 to 0 step -1
p = w*h-spiral(w,h,j,i)
print mid$(" o", is_prime(p) + 1, 1);
next
print
next</syntaxhighlight>
 
=={{header|zkl}}==
Line 2,869 ⟶ 5,940:
 
Using [[Extensible prime generator#zkl]] and the PPM class from http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm#zkl.
<langsyntaxhighlight lang="zkl">var primes =Utils.Generator(Import("sieve.zkl").postponed_sieve); // lazy
var offsets=Utils.Helpers.cycle( T(0,1),T(-1,0),T(0,-1),T(1,0) ); // (N,E,S,W), lazy
const BLACK=0, WHITE=0xffffff0xff|ff|ff, GREEN=0x00ff00, RED=0xff00000x00|ff|00, EMPTY=0x08080800x080|80|80;
fcn uspiral(N,n=1){
if((M:=N).isEven) M+=1; // need odd width, height
img,p := PPM(M,M,EMPTY), primes.next(); // 2 .. 250,007: 22,045 primes
x,y,n := N/2,x,2; img[x,y]=GREEN; x+=1; // start on 2 facing "north"
// collect all primes<=N*N+n
ps:=primes.filter('wrap(p){ p<=N*N+n and True or Void.Stop });
x:=N/2; y:=x; img[x,y]=GREEN; n+=1; x+=1;
while(True){
ox,oy:=offsets.next(); leftx,lefty:=offsets.peek(); // set direction
while(True){
img[x,y]=( if(psn==p){ p=primes.holdsnext(n)); WHITE } else BLACK );
if(n==N*N) break(2); // all done
n+=1;
if(img[x+leftx,y+lefty]==EMPTY) // nothing to my left, turn left
{ x+=leftx; y+=lefty; break; }
x+=ox; y+=oy; // move in a straight line
}
}
img
}
 
uspiral(501).write(File("foo.ppm","wb"));</lang>
uspiral(500).write(File("ulamSpiral.ppm","wb"));</syntaxhighlight>
{{out}}
A PPM image similar to that shown in Perl6Raku but denser. A green dot marks the center.
 
http://www.zenkinetic.com/Images/RosettaCode/ulamSpiral.png
 
 
=={{header|ZX Spectrum Basic}}==
a simplistic naive procedure that on a real machine will take some DAYS at the max of 176x176 numbers to check
 
RUN 10 , to start
 
 
<syntaxhighlight lang="ZX Spectrum Basic">
 
1 IF n<max THEN LET n=n+1: FOR p=2 TO n-1: LET r= (INT (n/p)<>n/p): IF r THEN NEXT p
2 IF p=n THEN LET pr=pr+1: LET kx=(255-xx AND k<3)+(xx AND k>2): LET ky=(175-yy AND (k=1 OR k=3)+(yy AND (k=2 OR k=4))): PLOT kx,ky: PRINT #0;AT 0,0;n;" pr";pr
3 RETURN
10 CLS : PRINT "ULAM SPIRAL OF PRIME's"'''"it takes DAYS at max level"'"and 3.5MHz"
12 INPUT "square size= LxL"'"l: ";l: IF l<>INT l OR l<1 OR l>176 THEN GO TO 12
13 LET max=l*l: PRINT ''l;"x";l;"=";max;" positive integers"
15 INPUT "0,0 orientation 1-4: ";k: IF k<1 OR k>4 THEN GO TO 15
20 CLS : LET xx=127: LET yy=88: LET n=0: LET pr=0: PRINT #0;AT 0,15;max
40 FOR q=0 TO l: LET m=INT (q/2)=q/2: LET m=-1*m+NOT m
60 FOR x=0 TO q*m STEP m: GO SUB 1 : LET xx=xx+m: NEXT x
80 FOR y=0 TO q*m STEP m: GO SUB 1 : LET yy=yy+m: NEXT y: NEXT q
9,485

edits