The Challenge
The shortest code by character count to output Ulam's spiral with a spiral size given by user input.
Ulam's spiral is one method to map prime numbers. The spiral starts from the number 1 being in the center (1 is not a prime) and generating a spiral around it, marking all prime numbers as the character '*
'. A non prime will be printed as a space ''.
alt text http://liranuna.com/junk/ulam.gif
Test cases
Input:
2
Output:
* *
*
*
Input:
3
Output:
* *
* *
* **
*
*
Input:
5
Output:
* *
* *
* * *
* * *
* ** *
* *
* *
* *
* *
Code count includes input/output (i.e full program).
C,
208206201200199196194193194193188185183180176 Bytes(if newlines are removed):
Compiled with
Warning. This program is slow, because is does a trial division up to 2^31. But is does produce the required output:
In nicely formatted C and with redundant #includes:
It works by transforming the coordinates of the grid to the appropriate number and then performing the primality test, intead of drawing in a snake-like manner. The different equations for the four "quadrants" can be collapsed into one with swapping x and y and an additional term for "backward counting".
MATLAB:
182167156 charactersScript
ulam.m
:And formatted a little nicer:
Test cases:
J solution:
197 173 165161 bytes (so far)this does not use the method mentioned in the comments to the OP
Python 2.x,
220C213C207C204C201C198C196C188CSpecial thanks to gnibbler for some hints in
#stackoverflow
on Freenode. Output includes a leading and trailing newline.(Python 3 compatibility would require extra chars; this uses
input
, theprint
statement and/
for integer division.)Lua, 302 characters
Output from
lua ulam.lua 6
:Python - 203 Characters
How it works
The idea is to fill A with x,y coords that need to be printed as '*'
The algorithm starts at the cell corresponding to 2, so the special case of testing 1 for primality is avoided.
x,y is the cell of interest
j,k keep track of whether we need to inc or dec x or y to get to the next cell
s is the value of i at the next corner
t keeps track of the increment to s
all(i%d for d in R(2,i)) does the primality check
The last line is rather clumsy. It iterates over all the cells and decides whether to place a space or an asterisk