Ulam spiral (for primes): Difference between revisions

m
m (→‎{{header|Wren}}: Minor tidy)
 
(33 intermediate revisions by 14 users not shown)
Line 117:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F cell(n, =x, =y, start = 1)
V d = 0
y = y - n I/ 2
Line 152:
 
show_spiral(10, symbol' ‘# ’, space' ‘ ’)
show_spiral(9, symbol' ‘’, space' ‘ - ’)</langsyntaxhighlight>
 
{{out}}
Line 181:
{{trans|Fortran}}
Compacted and optimized solution.
<langsyntaxhighlight lang="360asm">* Ulam spiral 26/04/2016
ULAM CSECT
USING ULAM,R13 set base register
Line 325:
SPIRAL DC (NS*NS)CL1' '
YREGS
END ULAM</langsyntaxhighlight>
{{out}}
<pre>
Line 354:
The specification of package generic_ulam is as follows:
 
<langsyntaxhighlight Adalang="ada">generic
Size: Positive;
-- determines the size of the square
Line 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 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 440:
NL;
Visual.Print_Spiral;
end Ulam;</langsyntaxhighlight>
 
{{out}}
Line 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 574 ⟶ 660:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
Run with a side-length of 29
Line 640 ⟶ 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 669 ⟶ 755:
}
return 0;
}</langsyntaxhighlight>
 
=={{header|C++}}==
=== parametric version ===
<langsyntaxhighlight lang="cpp">#include <cmath>
#include <iostream>
#include <string>
Line 773 ⟶ 859:
ulam.display( '#' );
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 825 ⟶ 911:
=== generic version ===
ulam.hpp
<langsyntaxhighlight lang="cpp">#pragma once
 
#include <cmath>
Line 889 ⟶ 975:
}
return os;
}</langsyntaxhighlight>
ulam.cpp
<langsyntaxhighlight lang="cpp">#include <cstdlib>
#include <iostream>
#include "ulam.hpp"
Line 903 ⟶ 989:
 
return EXIT_SUCCESS;
}</langsyntaxhighlight>
{{out}}
<pre>[ --- --- --- --- 61 --- 59 --- ---]
Line 926 ⟶ 1,012:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">
(defun ulam-spiral (n)
(loop for a in (spiral n n (* n n)) do
Line 943 ⟶ 1,029:
(when (> n 1) (loop for a from 2 to (isqrt n)
never (zerop (mod n a)))))
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,092 ⟶ 1,178:
=={{header|Crystal}}==
{{trans|Go}}
<langsyntaxhighlight lang="ruby">enum Direction
RIGHT
UP
Line 1,154 ⟶ 1,240:
 
puts generate 7, 1, "*"
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,169 ⟶ 1,255:
=={{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 1,202 ⟶ 1,288:
void main() {
35.showSpiral;
}</langsyntaxhighlight>
{{out}}
<pre> # # # #
Line 1,242 ⟶ 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 1,274 ⟶ 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 1,284 ⟶ 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 1,321 ⟶ 1,657:
Ulam.show_spiral(9)
Ulam.show_spiral(25)
Ulam.show_spiral(25, ["#"," "])</langsyntaxhighlight>
 
{{out}}
Line 1,392 ⟶ 1,728:
 
=={{header|ERRE}}==
<langsyntaxhighlight ERRElang="erre">PROGRAM SPIRAL
 
!$INTEGER
Line 1,469 ⟶ 1,805:
!$DIM SPIRAL$[N,N]
GEN_ULAM(N,1)
END PROGRAM</langsyntaxhighlight>
{{out}}
<pre>
Line 1,496 ⟶ 1,832:
=={{header|Factor}}==
{{trans|J}}
<langsyntaxhighlight lang="factor">USING: arrays grouping kernel math math.combinatorics
math.matrices math.primes math.ranges math.statistics
prettyprint sequences sequences.repeating ;
Line 1,518 ⟶ 1,854:
: ulam-demo ( -- ) 21 ulam-spiral simple-table. ;
 
MAIN: ulam-demo</langsyntaxhighlight>
{{out}}
<pre>
Line 1,547 ⟶ 1,883:
{{works with|GNU Forth|0.7.0}}
All array manipulations were taken from Rosetta Code examples.
<langsyntaxhighlight lang="forth">
43 constant border \ grid size is border x border
border border * constant size
Line 1,649 ⟶ 1,985:
: ulam.spiral run.crawler leave.primes draw.grid ; \ draws the spiral. Execute this word to run.
</langsyntaxhighlight>
{{out}}
<pre style="height:60ex;overflow:scroll">
Line 1,703 ⟶ 2,039:
{{works with|Fortran|95 and later}}
Only works with odd sized squares
<langsyntaxhighlight lang="fortran">program ulam
implicit none
 
Line 1,778 ⟶ 2,114:
end if
end function
end program</langsyntaxhighlight>
Output:
<pre> O O O O O O O
Line 1,832 ⟶ 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,891 ⟶ 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. Trying 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>
Line 1,949 ⟶ 2,285:
This is actually better handled graphically.
 
<langsyntaxhighlight lang="freebasic">
#define SIZE 639
 
Line 1,987 ⟶ 2,323:
 
sleep
end</langsyntaxhighlight>
 
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Ulam_spiral}}
In [https://wiki.formulae.org/Ulam_spiral_(for_primes) this] page you can see the solution of this task.
 
'''Solution'''
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text ([http://wiki.formulae.org/Editing_F%C5%8Drmul%C3%A6_expressions more info]). Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for transportation effects more than visualization and edition.
 
[[File:Fōrmulæ - Ulam spiral 01.png]]
The option to show Fōrmulæ programs and their results is showing images. Unfortunately images cannot be uploaded in Rosetta Code.
 
'''Test case'''
 
[[File:Fōrmulæ - Ulam spiral 02.png]]
 
[[File:Fōrmulæ - Ulam spiral 03.png]]
 
=={{header|Go}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 2,058 ⟶ 2,400:
generate(9, 1, 0) // with digits
generate(9, 1, '*') // with *
}</langsyntaxhighlight>
 
=={{header|Haskell}}==
Line 2,072 ⟶ 2,414:
As a program the given task then formulates as following:
 
<langsyntaxhighlight lang="haskell">import Data.List
import Data.Numbers.Primes
 
ulam n representation = swirl n . map representation </langsyntaxhighlight>
 
Here we refference the function <code>swirl n</code>, which for a given (possibly infinite) list returns <code>n</code> whorls of a spiral.
Line 2,081 ⟶ 2,423:
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:
 
<langsyntaxhighlight lang="haskell">swirl n = spool . take (2*(n-1)+1) . chop 1
 
chop n lst = let (x,(y,z)) = splitAt n <$> splitAt n lst
Line 2,087 ⟶ 2,429:
 
spool = foldl (\table piece -> piece : rotate table) [[]]
where rotate = reverse . transpose</langsyntaxhighlight>
 
That's it!
Line 2,095 ⟶ 2,437:
Pretty printing the table of strings with given column width is simple:
 
<langsyntaxhighlight lang="haskell">showTable w = foldMap (putStrLn . foldMap pad)
where pad s = take w $ s ++ repeat ' '</langsyntaxhighlight>
 
{{Out}}
Line 2,187 ⟶ 2,529:
 
Simple graphical output could be done using <code>Diagrams</code> framework:
<langsyntaxhighlight Haskelllang="haskell">import Diagrams.Prelude
import Diagrams.Backend.SVG.CmdLine
 
Line 2,194 ⟶ 2,536:
dots x = (circle 1 # if isPrime x then fc black else fc white) :: Diagram B
 
main = mainWith $ drawTable $ ulam 100 dots [1..]</langsyntaxhighlight>
 
=={{header|J}}==
Line 2,200 ⟶ 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 2,215 ⟶ 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 2,276 ⟶ 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 2,286 ⟶ 2,628:
=={{header|Java}}==
{{works with|Java|1.5+}}
<langsyntaxhighlight lang="java5">import java.util.Arrays;
 
public class Ulam{
Line 2,349 ⟶ 2,691:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>[ --- --- --- --- 61 --- 59 --- ---]
Line 2,374 ⟶ 2,716:
[[File:ulam_large_java.gif|300px|thumb|right]]
{{works with|Java|8}}
<langsyntaxhighlight lang="java">import java.awt.*;
import javax.swing.*;
 
Line 2,440 ⟶ 2,782:
});
}
}</langsyntaxhighlight>
 
=== Small scale Ulam Spiral ===
[[File:ulam_spiral_java.gif|300px|thumb|right]]
{{works with|Java|8}}
<langsyntaxhighlight lang="java">import java.awt.*;
import javax.swing.*;
 
Line 2,523 ⟶ 2,865:
});
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
Line 2,533 ⟶ 2,875:
{{trans|PARI/GP}}
{{Works with|Chrome}} (or any other browser supporting Canvas tag)
<langsyntaxhighlight lang="html">
<!-- UlamSpiral.html -->
<html>
Line 2,641 ⟶ 2,983:
</body>
</html>
</langsyntaxhighlight>
{{Output}}
 
Line 2,683 ⟶ 3,025:
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}}
 
<langsyntaxhighlight lang="julia">using Primes
 
function ulamspiral(ord::Int)
Line 2,717 ⟶ 3,113:
 
M = ulamspiral(9)
mprint(M)</langsyntaxhighlight>
 
{{out}}
Line 2,740 ⟶ 3,136:
=={{header|Kotlin}}==
{{trans|Java}}
<langsyntaxhighlight lang="scala">object Ulam {
fun generate(n: Int, i: Int = 1, c: Char = '*') {
require(n > 1)
Line 2,787 ⟶ 3,183:
Ulam.generate(9, c = '0')
Ulam.generate(9)
}</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">local function ulamspiral(n, f)
print("n = " .. n)
local function isprime(p)
Line 2,817 ⟶ 3,213:
 
-- filling a 132 column terminal (with a 2-wide glyph to better preserve aspect ratio)
ulamspiral(132/2, function(b) return b and "██" or " " end)</langsyntaxhighlight>
{{out}}
<pre>n = 66.0
Line 2,887 ⟶ 3,283:
██ ██ ██ ██ ██
</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}}==
<langsyntaxhighlight Mathematicalang="mathematica">ClearAll[iCCWSpiralEast]
iCCWSpiralEast[n_Integer]:=Table[(1/2 (-1)^# ({1,-1} (Abs[#^2-t]-#)+#^2-t-Mod[#,2])&)[Round[Sqrt[t]]],{t,0,n-1}]
n=20
Line 2,896 ⟶ 3,383:
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]</langsyntaxhighlight>
{{out}}
<pre> * * *
Line 2,918 ⟶ 3,405:
* * *
* * * * </pre>
 
=={{header|Maxima}}==
[[File:Ulam spiral.png|thumb|Ulam spiral powered by Maxima]]
Using the function defined in the Spiral matrix task
<syntaxhighlight lang="maxima">
/* 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===
<langsyntaxhighlight Nimlang="nim">import strutils
 
const N = 51 # Grid width and height.
Line 2,982 ⟶ 3,481:
grid.fill()
for row in grid:
echo row.join()</langsyntaxhighlight>
 
{{out}}
Line 3,041 ⟶ 3,540:
Writing in a file, it is possible to create much bigger images.
 
<langsyntaxhighlight Nimlang="nim">import imageman
 
const
Line 3,111 ⟶ 3,610:
image.fill(BG)
image.apply(grid)
image.savePNG("ulam_spiral.png", compression = 9)</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
Line 3,123 ⟶ 3,622:
{{Works with|PARI/GP|2.7.4 and above}}
 
<langsyntaxhighlight lang="parigp">
\\ Ulam spiral (plotting/printing)
\\ 4/19/16 aev
Line 3,154 ⟶ 3,653:
plotulamspir(200); \\ ULAMspiral2.png
}
</langsyntaxhighlight>
 
{{Output}}
Line 3,198 ⟶ 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 3,385 ⟶ 3,884:
Until (wot <= 0) or (wot > Mstyle); {Alas, "Enter" must be pressed.}
END.
</syntaxhighlight>
</lang>
=== using FreePascal ===
{{works with|FreePascalFree Pascal|3.2.0 }}
<syntaxhighlight lang="pascal">
<lang Pascal>
PROGRAM Ulam.pas;
 
Line 3,402 ⟶ 3,901:
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 *
 
https://www.freepascal.org/advantage.var
(*)
 
Line 3,546 ⟶ 4,047:
 
END.
</langsyntaxhighlight>JPD 2021/06/14
Output:
61 59
Line 3,568 ⟶ 4,069:
, ,
, ,
 
 
=== using FreePascal (short version) ===
{{works with|FreePascalFree Pascal| 3.2.0 }}
<syntaxhighlight lang="pascal">
<lang Pascal>
PROGRAM Ulam8.pas;
 
Line 3,591 ⟶ 4,091:
For debian Linux: apt -y install fpc
It contains a text IDE called fp
 
https://www.freepascal.org/advantage.var
 
(*)
Line 3,600 ⟶ 4,102:
CONST
 
SIZE = 89 ; // `SIZE = 9 : "The Iceskater" ( Obvious when Dutch ) `
n = SIZE * ord ( Odd ( SIZE ) ) ;
 
Line 3,676 ⟶ 4,178:
 
END.
</langsyntaxhighlight>JPD 2021/07/04
Output:
61 59
Line 3,701 ⟶ 4,203:
=={{header|Perl}}==
{{trans|python}}{{libheader|ntheory}}
<langsyntaxhighlight lang="perl">use ntheory qw/is_prime/;
use Imager;
 
Line 3,729 ⟶ 4,231:
}
 
$img->write(file => $file) or die "Cannot write $file: ", $img->errstr, "\n";</langsyntaxhighlight>
{{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.
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>function spiral(integer w, h, x, y)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
return iff(y?w+spiral(h-1,w,y-1,w-x-1):x)
<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>
end function
<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>
integer w = 9, h = 9
for i=h-1 to 0 by -1 do
<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>
for j=w-1 to 0 by -1 do
<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>
integer p = w*h-spiral(w,h,j,i)
<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>
puts(1,"o "[2-is_prime(p)])
<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>
end for
<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>
puts(1,'\n')
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end for</lang>
<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>
Line 3,758 ⟶ 4,263:
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">-->
<lang Phix>sequence vc = video_config()
<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>
integer w = vc[VC_SCRNCOLS]-1, h = vc[VC_SCRNLINES]-1</lang>
<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 3,808 ⟶ 4,315:
(ulam 9) )
 
(bye)</langsyntaxhighlight>
{{out}}
<pre>
Line 3,823 ⟶ 4,330:
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function New-UlamSpiral ( [int]$N )
{
Line 3,864 ⟶ 4,371:
 
New-UlamSpiral 100
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,970 ⟶ 4,477:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python"># coding=UTF-8
from __future__ import print_function, division
from math import sqrt
Line 4,005 ⟶ 4,512:
show_spiral(9, symbol='', space=' - ')
# for filling giant terminals
#show_spiral(1001, symbol='*', start=42)</langsyntaxhighlight>
{{out}}
<pre>
Line 4,028 ⟶ 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>
 
Line 4,040 ⟶ 4,599:
[[File:UlamSpiralR2.png|200px|right|thumb|Output UlamSpiralR2.png]]
 
<syntaxhighlight lang="r">
<lang r>
## Plotting Ulam spiral (for primes) 2/12/17 aev
## plotulamspirR(n, clr, fn, ttl, psz=600), where: n - initial size;
Line 4,071 ⟶ 4,630:
plotulamspirR(100, "red", "UlamSpiralR1", "Ulam Spiral: ");
plotulamspirR(200, "red", "UlamSpiralR2", "Ulam Spiral: ",1240);
</langsyntaxhighlight>
 
{{Output}}
Line 4,093 ⟶ 4,652:
{{trans|Python}}
 
<langsyntaxhighlight lang="racket">#lang racket
(require (only-in math/number-theory prime?))
Line 4,128 ⟶ 4,687:
(show-spiral 50 #:symbol "*" #:start 42)
; for filling giant terminals
; (show-spiral 1001 #:symbol "*" #:start 42)</langsyntaxhighlight>
 
{{out}}
Line 4,204 ⟶ 4,763:
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line>sub MAIN($max = 160, $start = 1) {
(my %world){0}{0} = 0;
my ($n, $dir, $side, $loc) = $start, 1, 0, 0+0i;
my $dir = 1;
my $n = $start;
my $side = 0;
 
while ++$side < $max {
step for ^$side; turn-left;
step for ^$side; turn-left;
step for ^$side;
turn-left;
}
 
Line 4,225 ⟶ 4,779:
}
 
sub turn-left { $dir *×= -i; }
sub turn-right { $dir *×= i; }
 
}
 
sub braille-graphics (%a) {
my ($yloy-lo, $yhiy-hi, $xlox-lo, $xhix-hi);
for %a.keys.map(+*) -> $\y {
for %a{y}.keys.map(+*) -> \x {
$ylo min= +$y; $yhi max= +$y;
$y-lo min= y; $y-hi max= y;
for %a{$y}.keys -> $x {
$xlox-lo min= +$x; $xhix-hi max= +$x;
}
}
}
 
for $yloy-lo, $yloy-lo + 4 ...^ * > $yhiy-hi -> \y {
for $xlox-lo, $xlox-lo + 2 ...^ * > $xhix-hi -> \x {
my $cell = 0x2800;
$cell += 1 2⁰ if %a{y + 0}{x + 0};
$cell += 2 ¹ if %a{y + 1}{x + 0};
$cell += 4 if %a{y + 2}{x + 0};
$cell += 8 if %a{y + 0}{x + 1};
$cell += 16 2⁴ if %a{y + 1}{x + 1};
$cell += 32 2⁵ if %a{y + 2}{x + 1};
$cell += 64 2⁶ if %a{y + 3}{x + 0};
$cell += 1282⁷ if %a{y + 3}{x + 1};
print chr($cell);
}
print "\n";
}
}</langsyntaxhighlight>
{{out}}
<pre>⠔⠀⠀⠀⢐⠀⠁⠀⠀⠀⢐⠁⠀⢀⠀⠄⠄⠀⢀⠀⠀⠅⢀⠁⢅⢄⠀⢀⠔⠁⠀⠀⠀⢀⢀⠀⠀⠀⠁⢀⢀⠀⠀⢔⠁⢔⠄⠀⢄⠐⠀⠀⢀⠁⠐⠄⠀⢑⠄⠁⠄⠀⠁⠄⠀⠀⠀⢐⠀⠄⠐⠀⢁⢀⠀⠀⠄⠀⢕⠐
Line 4,321 ⟶ 4,874:
===counter-clockwise===
<langsyntaxhighlight lang="rexx">/*REXX program shows counter─clockwise Ulam spiral of primes shown in a square matrix.*/
parse arg size init char . /*obtain optional arguments from the CL*/
if size=='' | size=="," then size= 79 /*Not specified? Then use the default.*/
Line 4,368 ⟶ 4,921:
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</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
 
Line 4,467 ⟶ 5,020:
===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 program shows a clockwise Ulam spiral of primes shown in a square matrix.*/
parse arg size init char . /*obtain optional arguments from the CL*/
if size=='' | size=="," then size= 79 /*Not specified? Then use the default.*/
Line 4,514 ⟶ 5,067:
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</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
 
Line 4,564 ⟶ 5,117:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Ulam spiral (for primes)
Line 4,666 ⟶ 5,219:
next
}
</syntaxhighlight>
</lang>
Outputimage:
 
Line 4,674 ⟶ 5,227:
It finds the number from the position ( the coordinates ).
{{trans|Python}}
<langsyntaxhighlight lang="ruby">require 'prime'
 
def cell(n, x, y, start=1)
Line 4,701 ⟶ 5,254:
show_spiral(9)
show_spiral(25)
show_spiral(25, "# ")</langsyntaxhighlight>
 
{{out}}
Line 4,773 ⟶ 5,326:
===Another Version===
computes the next spiral position.
<langsyntaxhighlight lang="ruby">require 'prime'
 
def spiral_generator(x=0, y=0)
Line 4,808 ⟶ 5,361:
puts "\nN : #{n}"
ulam_spiral(n)
end</langsyntaxhighlight>
 
{{out}}
Line 4,888 ⟶ 5,441:
{{trans|Kotlin}}
{{works with|Rust|1.11.0}}
<langsyntaxhighlight lang="rust">use std::fmt;
 
enum Direction { RIGHT, UP, LEFT, DOWN }
Line 4,945 ⟶ 5,498:
writeln!(f, "")
}
}</langsyntaxhighlight>
main.rs :
<langsyntaxhighlight lang="rust">mod ulam;
use ulam::*;
 
Line 4,954 ⟶ 5,507:
print!("{}", Ulam::new(9, 1, '\0'));
print!("{}", Ulam::new(9, 1, '*'));
}</langsyntaxhighlight>
{{out}}
<pre>[ --- --- --- --- 61 --- 59 --- ---]
Line 4,978 ⟶ 5,531:
=={{header|Scala}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="scala">object Ulam extends App {
generate(9)()
generate(9)('*')
Line 5,020 ⟶ 5,573:
true
}
}</langsyntaxhighlight>
 
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">require('Imager')
 
var (n=512, start=1, file='ulam.png')
Line 5,054 ⟶ 5,607:
}
 
img.write(file => file)</langsyntaxhighlight>
Output image: [https://github.com/trizen/rc/blob/master/img/ulam-spiral-sidef.png Ulam spiral]
 
Line 5,061 ⟶ 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 5,111 ⟶ 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 5,150 ⟶ 5,703:
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
Function build_spiral(n)
'declare a two dimentional array
Line 5,231 ⟶ 5,784:
'test with 9
build_spiral(9)
</syntaxhighlight>
</lang>
 
{{Out}}
Line 5,252 ⟶ 5,805:
{{libheader|Wren-str}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight ecmascriptlang="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"])
Line 5,296 ⟶ 5,849:
 
Ulam.generate(9, 1, "0") // with digits
Ulam.generate(9, 1, "*") // with *</langsyntaxhighlight>
 
{{out}}
Line 5,320 ⟶ 5,873:
* --- --- --- --- --- * --- ---
</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}}
<langsyntaxhighlight Yabasiclang="yabasic">sub is_prime(n)
local p
Line 5,348 ⟶ 5,934:
next
print
next</langsyntaxhighlight>
 
=={{header|zkl}}==
Line 5,354 ⟶ 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.cycle( T(0,1),T(-1,0),T(0,-1),T(1,0) ); // (N,E,S,W), lazy
const BLACK=0, WHITE=0xff|ff|ff, GREEN=0x00|ff|00, EMPTY=0x080|80|80;
Line 5,375 ⟶ 5,961:
}
 
uspiral(500).write(File("ulamSpiral.ppm","wb"));</langsyntaxhighlight>
{{out}}
A PPM image similar to that shown in Raku 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,476

edits