Code Golf: Ulam Spiral

2019-03-09 08:51发布

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条回答
Juvenile、少年°
2楼-- · 2019-03-09 09:17

Ruby - 158 Characters

Same algorithm as this one, just the prime test is different

p=(v=(w=gets.to_i*2)-1)*w/2-1
a='
'*v*w
d=0
(v*v).times{|i|a[p]="1"*(i+1)!~/^1?$|^(11+?)\1+$/?42:32;d=(a[p+(z=[w,-1,-w,1])[d-1]]<32)?(d-1):d%4;p+=z[d]}
puts a
查看更多
登录 后发表回答