Ulam spiral (for primes): Difference between revisions
m
syntax highlighting fixup automation
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
|||
Line 117:
{{trans|Python}}
<
V d = 0
y = y - n I/ 2
Line 152:
show_spiral(10, symbol' ‘# ’, space' ‘ ’)
show_spiral(9, symbol' ‘’, space' ‘ - ’)</
{{out}}
Line 181:
{{trans|Fortran}}
Compacted and optimized solution.
<
ULAM CSECT
USING ULAM,R13 set base register
Line 325:
SPIRAL DC (NS*NS)CL1' '
YREGS
END ULAM</
{{out}}
<pre>
Line 354:
The specification of package generic_ulam is as follows:
<
Size: Positive;
-- determines the size of the square
Line 372:
-- and New_Line N times
end Generic_Ulam;</
Here is the implementation:
<
subtype Index is Natural range 0 .. Size-1;
Line 410:
end Print_Spiral;
end Generic_Ulam;</
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]].
<
procedure Ulam is
Line 440:
NL;
Visual.Print_Spiral;
end Ulam;</
{{out}}
Line 486:
=={{header|C}}==
<syntaxhighlight lang="c">
#include <stdio.h>
#include <stdint.h>
Line 574:
return 0;
}
</syntaxhighlight>
{{out}}
Run with a side-length of 29
Line 640:
The following shows a spiral that's not necessarily square, which has questionable merit:
<
#include <stdlib.h>
Line 669:
}
return 0;
}</
=={{header|C++}}==
=== parametric version ===
<
#include <iostream>
#include <string>
Line 773:
ulam.display( '#' );
return 0;
}</
{{out}}
<pre>
Line 825:
=== generic version ===
ulam.hpp
<
#include <cmath>
Line 889:
}
return os;
}</
ulam.cpp
<
#include <iostream>
#include "ulam.hpp"
Line 903:
return EXIT_SUCCESS;
}</
{{out}}
<pre>[ --- --- --- --- 61 --- 59 --- ---]
Line 926:
=={{header|Common Lisp}}==
<
(defun ulam-spiral (n)
(loop for a in (spiral n n (* n n)) do
Line 943:
(when (> n 1) (loop for a from 2 to (isqrt n)
never (zerop (mod n a)))))
</syntaxhighlight>
{{out}}
Line 1,092:
=={{header|Crystal}}==
{{trans|Go}}
<
RIGHT
UP
Line 1,154:
puts generate 7, 1, "*"
</syntaxhighlight>
{{out}}
Line 1,169:
=={{header|D}}==
{{trans|python}}
<
int cell(in int n, int x, int y, in int start=1) pure nothrow @safe @nogc {
Line 1,202:
void main() {
35.showSpiral;
}</
{{out}}
<pre> # # # #
Line 1,242:
===Alternative Version===
This generates a PGM image, using the module from the Grayscale Image Task;
<
uint cell(in uint n, int x, int y, in uint start=1) pure nothrow @safe @nogc {
Line 1,274:
img.savePGM("ulam_spiral.pgm");
}</
=={{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] .
<
(lib 'plot)
Line 1,284:
(define (ulam n nmax) (if ( prime? n) *red* (gray (// n nmax))))
(plot-spiral ulam 1000) ;; range [0...1000]
</syntaxhighlight>
=={{header|Elixir}}==
{{trans|Ruby}}
<
defp cell(n, x, y, start) do
y = y - div(n, 2)
Line 1,321:
Ulam.show_spiral(9)
Ulam.show_spiral(25)
Ulam.show_spiral(25, ["#"," "])</
{{out}}
Line 1,392:
=={{header|ERRE}}==
<
!$INTEGER
Line 1,469:
!$DIM SPIRAL$[N,N]
GEN_ULAM(N,1)
END PROGRAM</
{{out}}
<pre>
Line 1,496:
=={{header|Factor}}==
{{trans|J}}
<
math.matrices math.primes math.ranges math.statistics
prettyprint sequences sequences.repeating ;
Line 1,518:
: ulam-demo ( -- ) 21 ulam-spiral simple-table. ;
MAIN: ulam-demo</
{{out}}
<pre>
Line 1,547:
{{works with|GNU Forth|0.7.0}}
All array manipulations were taken from Rosetta Code examples.
<
43 constant border \ grid size is border x border
border border * constant size
Line 1,649:
: ulam.spiral run.crawler leave.primes draw.grid ; \ draws the spiral. Execute this word to run.
</
{{out}}
<pre style="height:60ex;overflow:scroll">
Line 1,703:
{{works with|Fortran|95 and later}}
Only works with odd sized squares
<
implicit none
Line 1,778:
end if
end function
end program</
Output:
<pre> O O O O O O O
Line 1,832:
===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">
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:
CALL ULAMSPIRAL(1,49)
END
</syntaxhighlight>
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:
This is actually better handled graphically.
<
#define SIZE 639
Line 1,987:
sleep
end</
=={{header|Fōrmulæ}}==
Line 1,999:
=={{header|Go}}==
{{trans|Kotlin}}
<
import (
Line 2,058:
generate(9, 1, 0) // with digits
generate(9, 1, '*') // with *
}</
=={{header|Haskell}}==
Line 2,072:
As a program the given task then formulates as following:
<
import Data.Numbers.Primes
ulam n representation = swirl n . map representation </
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:
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:
<
chop n lst = let (x,(y,z)) = splitAt n <$> splitAt n lst
Line 2,087:
spool = foldl (\table piece -> piece : rotate table) [[]]
where rotate = reverse . transpose</
That's it!
Line 2,095:
Pretty printing the table of strings with given column width is simple:
<
where pad s = take w $ s ++ repeat ' '</
{{Out}}
Line 2,187:
Simple graphical output could be done using <code>Diagrams</code> framework:
<
import Diagrams.Backend.SVG.CmdLine
Line 2,194:
dots x = (circle 1 # if isPrime x then fc black else fc white) :: Diagram B
main = mainWith $ drawTable $ ulam 100 dots [1..]</
=={{header|J}}==
Line 2,200:
Let's start with our implementation of [[Spiral_matrix#J|spiral]]:
<
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:
<
0 1 2 3 4
15 16 17 18 5
Line 2,215:
11 2 1 6 19
12 3 4 5 18
13 14 15 16 17</
Next, we want to determine which of these numbers are prime:
<
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</
And, finally, we want to use these values to select from a pair of characters:
<
o
o
oo o
o o
o o</
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):
<
0
3 (0: :(<:@[)) ''
2</
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:
<
And here it is in action:
<
o o
o o o
Line 2,276:
o o o o
o
o o o </
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:
=={{header|Java}}==
{{works with|Java|1.5+}}
<
public class Ulam{
Line 2,349:
}
}
}</
{{out}}
<pre>[ --- --- --- --- 61 --- 59 --- ---]
Line 2,374:
[[File:ulam_large_java.gif|300px|thumb|right]]
{{works with|Java|8}}
<
import javax.swing.*;
Line 2,440:
});
}
}</
=== Small scale Ulam Spiral ===
[[File:ulam_spiral_java.gif|300px|thumb|right]]
{{works with|Java|8}}
<
import javax.swing.*;
Line 2,523:
});
}
}</
=={{header|JavaScript}}==
Line 2,533:
{{trans|PARI/GP}}
{{Works with|Chrome}} (or any other browser supporting Canvas tag)
<
<!-- UlamSpiral.html -->
<html>
Line 2,641:
</body>
</html>
</
{{Output}}
Line 2,690:
See [[Erdős-primes#jq]] for a suitable definition of `is_prime` as used here.
<
# Test if input is a one-character string holding a digit
Line 2,734:
# with *
generate(9; 1; "*")
</syntaxhighlight>
{{out}}
As for [[#Wren|Wren]].
Line 2,741:
{{works with|Julia|0.6}}
<
function ulamspiral(ord::Int)
Line 2,771:
M = ulamspiral(9)
mprint(M)</
{{out}}
Line 2,794:
=={{header|Kotlin}}==
{{trans|Java}}
<
fun generate(n: Int, i: Int = 1, c: Char = '*') {
require(n > 1)
Line 2,841:
Ulam.generate(9, c = '0')
Ulam.generate(9)
}</
=={{header|Lua}}==
<
print("n = " .. n)
local function isprime(p)
Line 2,871:
-- 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)</
{{out}}
<pre>n = 66.0
Line 2,943:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
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,950:
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]</
{{out}}
<pre> * * *
Line 2,976:
===Displaying in terminal===
<
const N = 51 # Grid width and height.
Line 3,036:
grid.fill()
for row in grid:
echo row.join()</
{{out}}
Line 3,095:
Writing in a file, it is possible to create much bigger images.
<
const
Line 3,165:
image.fill(BG)
image.apply(grid)
image.savePNG("ulam_spiral.png", compression = 9)</
=={{header|PARI/GP}}==
Line 3,177:
{{Works with|PARI/GP|2.7.4 and above}}
<
\\ Ulam spiral (plotting/printing)
\\ 4/19/16 aev
Line 3,208:
plotulamspir(200); \\ ULAMspiral2.png
}
</
{{Output}}
Line 3,252:
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">
Program Ulam; Uses crt;
{Concocted by R.N.McLean (whom God preserve), ex Victoria university, NZ.}
Line 3,439:
Until (wot <= 0) or (wot > Mstyle); {Alas, "Enter" must be pressed.}
END.
</syntaxhighlight>
=== using FreePascal ===
{{works with|Free Pascal|3.2.0 }}
<syntaxhighlight lang="pascal">
PROGRAM Ulam.pas;
Line 3,602:
END.
</
Output:
61 59
Line 3,627:
=== using FreePascal (short version) ===
{{works with|Free Pascal| 3.2.0 }}
<syntaxhighlight lang="pascal">
PROGRAM Ulam8.pas;
Line 3,733:
END.
</
Output:
61 59
Line 3,758:
=={{header|Perl}}==
{{trans|python}}{{libheader|ntheory}}
<
use Imager;
Line 3,786:
}
$img->write(file => $file) or die "Cannot write $file: ", $img->errstr, "\n";</
{{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}}==
<!--<
<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>
Line 3,805:
<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>
<!--</
{{out}}
<pre>
Line 3,819:
</pre>
For something that almost fills your entire screen (not pwa/p2js compatible), change the definition of w and h to
<!--<
<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>
<!--</
=={{header|PicoLisp}}==
<
(de ceil (A)
Line 3,870:
(ulam 9) )
(bye)</
{{out}}
<pre>
Line 3,885:
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
function New-UlamSpiral ( [int]$N )
{
Line 3,926:
New-UlamSpiral 100
</syntaxhighlight>
{{out}}
<pre>
Line 4,032:
=={{header|Python}}==
<
from __future__ import print_function, division
from math import sqrt
Line 4,067:
show_spiral(9, symbol='', space=' - ')
# for filling giant terminals
#show_spiral(1001, symbol='*', start=42)</
{{out}}
<pre>
Line 4,102:
[[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;
Line 4,133:
plotulamspirR(100, "red", "UlamSpiralR1", "Ulam Spiral: ");
plotulamspirR(200, "red", "UlamSpiralR2", "Ulam Spiral: ",1240);
</
{{Output}}
Line 4,155:
{{trans|Python}}
<
(require (only-in math/number-theory prime?))
Line 4,190:
(show-spiral 50 #:symbol "*" #:start 42)
; for filling giant terminals
; (show-spiral 1001 #:symbol "*" #:start 42)</
{{out}}
Line 4,266:
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku"
(my %world){0}{0} = 0;
my ($n, $dir, $side, $loc) = $start, 1, 0, 0+0i;
Line 4,310:
print "\n";
}
}</
{{out}}
<pre>⠔⠀⠀⠀⢐⠀⠁⠀⠀⠀⢐⠁⠀⢀⠀⠄⠄⠀⢀⠀⠀⠅⢀⠁⢅⢄⠀⢀⠔⠁⠀⠀⠀⢀⢀⠀⠀⠀⠁⢀⢀⠀⠀⢔⠁⢔⠄⠀⢄⠐⠀⠀⢀⠁⠐⠄⠀⢑⠄⠁⠄⠀⠁⠄⠀⠀⠀⢐⠀⠄⠐⠀⢁⢀⠀⠀⠄⠀⢕⠐
Line 4,377:
===counter-clockwise===
<
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,424:
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</
{{out|output|text= when using the default input:}}
Line 4,523:
===clockwise===
This REXX version is presented here to show the difference between a clockwise and a counter-clockwise Ulam (prime) spiral.
<
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,570:
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</
{{out|output|text= when using the default input:}}
Line 4,620:
=={{header|Ring}}==
<
# Project : Ulam spiral (for primes)
Line 4,722:
next
}
</syntaxhighlight>
Outputimage:
Line 4,730:
It finds the number from the position ( the coordinates ).
{{trans|Python}}
<
def cell(n, x, y, start=1)
Line 4,757:
show_spiral(9)
show_spiral(25)
show_spiral(25, "# ")</
{{out}}
Line 4,829:
===Another Version===
computes the next spiral position.
<
def spiral_generator(x=0, y=0)
Line 4,864:
puts "\nN : #{n}"
ulam_spiral(n)
end</
{{out}}
Line 4,944:
{{trans|Kotlin}}
{{works with|Rust|1.11.0}}
<
enum Direction { RIGHT, UP, LEFT, DOWN }
Line 5,001:
writeln!(f, "")
}
}</
main.rs :
<
use ulam::*;
Line 5,010:
print!("{}", Ulam::new(9, 1, '\0'));
print!("{}", Ulam::new(9, 1, '*'));
}</
{{out}}
<pre>[ --- --- --- --- 61 --- 59 --- ---]
Line 5,034:
=={{header|Scala}}==
{{trans|Kotlin}}
<
generate(9)()
generate(9)('*')
Line 5,076:
true
}
}</
=={{header|Sidef}}==
{{trans|Perl}}
<
var (n=512, start=1, file='ulam.png')
Line 5,110:
}
img.write(file => file)</
Output image: [https://github.com/trizen/rc/blob/master/img/ulam-spiral-sidef.png Ulam spiral]
Line 5,117:
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.
<
if {$n == 1} {return 0}
if {$n in {2 3 5}} {return 1}
Line 5,167:
}
puts [join [lmap row $cells {join $row " "}] \n]</
The mark used is Unicode's OGHAM FEATHER MARK .. the closest I could find to a Tcl logo.
Line 5,206:
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
Function build_spiral(n)
'declare a two dimentional array
Line 5,287:
'test with 9
build_spiral(9)
</syntaxhighlight>
{{Out}}
Line 5,308:
{{libheader|Wren-str}}
{{libheader|Wren-fmt}}
<
import "/math" for Int
import "/str" for Char
Line 5,352:
Ulam.generate(9, 1, "0") // with digits
Ulam.generate(9, 1, "*") // with *</
{{out}}
Line 5,378:
=={{header|XPL0}}==
<
int N, I;
[if N <= 2 then return N = 2;
Line 5,408:
Len:= Len+1;
until Y = 0; \reached top
]</
=={{header|Yabasic}}==
{{trans|Phix}}
<
local p
Line 5,437:
next
print
next</
=={{header|zkl}}==
Line 5,443:
Using [[Extensible prime generator#zkl]] and the PPM class from http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm#zkl.
<
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,464:
}
uspiral(500).write(File("ulamSpiral.ppm","wb"));</
{{out}}
A PPM image similar to that shown in Raku but denser. A green dot marks the center.
|