Here is my ASCII version of Ulam's spiral, ie. spiralling outwards not inwards.
use strict;
use warnings;
use Math::Prime::XS 'sieve_primes';
my $n = shift;
my %primes = map { $_ => 'O' } sieve_primes $n;
my @spiral;
my $o = 1 + int( sqrt( $n )/2 );
my ( $x, $y ) = ( $o, $o ); # starting point
my ( $xs, $ys ) = ( 1, 0 ); # initial direction
my $flip = 1; # change of direction indicator
my $m = 1; # length of current lag
for my $i ( 1..$n ) {
$spiral[$y][$x] = $primes{ $i }//' ';
$x += $xs; $y += $ys;
($xs, $ys) = ( ( $flip=1-$flip ) and $m++ ) ? ($ys, 0) : (0, -$xs)
+ unless $i%$m;
}
$spiral[$o][$o] = 'X';
print join '', map { $_//' '} @$_, "\n" for @spiral;