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).
Python, 299 characters:
Mathematica 243
Usage
13 windings:
MATLAB, 56 characters
based on @gnovice solution, improved by using MATLAB's spiral function :)
Test Cases:
My first code golf!
Ruby,
309301283271265 charactersHaskell - 224 characters
i'm not the best at haskell so there is probably some more shrinkage that can occur here
output from
echo 6 | runghc ulam.hs
this is a different algorithm (similar to @drhirsch's) unfortunately i cannot seem to get it below 239 characters
Ruby 1.8.7, 194 chars
For some reason, ruby1.9 wants another space on line 4: