Code Golf: Ulam Spiral

Viewed 4510

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).

19 Answers
Related