There's more than one way to do things PerlMonks

### Re: Spiraling integers

by hdb (Monsignor)
 on Jan 22, 2014 at 09:02 UTC ( #1071576=note: print w/replies, xml ) Need Help??

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;

Create A New User
Node Status?
node history
Node Type: note [id://1071576]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (6)
As of 2019-10-23 00:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
In 2019 the site I miss most is:

Results (57 votes). Check out past polls.

Notices?