The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

Math::PlanePath::SquareSpiral -- integer points drawn around a square (or rectangle)

SYNOPSIS

 use Math::PlanePath::SquareSpiral;
 my $path = Math::PlanePath::SquareSpiral->new;
 my ($x, $y) = $path->n_to_xy (123);

DESCRIPTION

This path makes a square spiral,

    37--36--35--34--33--32--31              3
     |                       |
    38  17--16--15--14--13  30              2
     |   |               |   |
    39  18   5---4---3  12  29              1
     |   |   |       |   |   |
    40  19   6   1---2  11  28  ...    <- Y=0
     |   |   |           |   |   |
    41  20   7---8---9--10  27  52         -1
     |   |                   |   |
    42  21--22--23--24--25--26  51         -2
     |                           |
    43--44--45--46--47--48--49--50         -3

                 ^
    -3  -2  -1  X=0  1   2   3   4

See examples/square-numbers.pl in the sources for a simple program printing these numbers.

This path is well known from Stanislaw Ulam finding interesting straight lines when plotting the prime numbers on it. See examples/ulam-spiral-xpm.pl in the sources for a program generating that, or see math-image using this SquareSpiral to draw Ulam's pattern and more.

Straight Lines

The perfect squares 1,4,9,16,25 fall on diagonals with the even perfect squares going to the upper left and the odd ones to the lower right. The pronic numbers 2,6,12,20,30,42 etc k^2+k half way between the squares fall on similar diagonals to the upper right and lower left. The decagonal numbers 10,27,52,85 etc 4*k^2-3*k go horizontally to the right at Y=-1.

In general straight lines and diagonals are 4*k^2 + b*k + c. b=0 is the even perfect squares up to the left, then b is an eighth turn counter-clockwise, or clockwise if negative. So b=1 is horizontally to the left, b=2 diagonally down to the left, b=3 down vertically, etc.

Honaker's prime-generating polynomial 4*k^2 + 4*k + 59 goes down to the right, after the first 30 or so values loop around a bit.

Wider

An optional wider parameter makes the path wider, becoming a rectangle spiral instead of a square. For example

    $path = Math::PlanePath::SquareSpiral->new (wider => 3);

gives

    29--28--27--26--25--24--23--22        2
     |                           |
    30  11--10-- 9-- 8-- 7-- 6  21        1
     |   |                   |   |
    31  12   1-- 2-- 3-- 4-- 5  20   <- Y=0
     |   |                       |
    32  13--14--15--16--17--18--19       -1
     |
    33--34--35--36-...                   -2

                     ^
    -4  -3  -2  -1  X=0  1   2   3

The centre horizontal 1 to 2 is extended by wider many further places, then the path loops around that shape. The starting point 1 is shifted to the left by ceil(wider/2) places to keep the spiral centred on the origin X=0,Y=0.

Widening doesn't change the nature of the straight lines which arise, it just rotates them around. For example in this wider=3 example the perfect squares are still on diagonals, but the even squares go towards the bottom left (instead of top left when wider=0) and the odd squares to the top right (instead of the bottom right).

Each loop is still 8 longer than the previous, as the widening is basically a constant amount in each loop.

Corners

Other spirals can be formed by cutting the corners of the square so as to go around faster. See the following modules,

    Corners Cut    Class
    -----------    -----
         1        HeptSpiralSkewed
         2        HexSpiralSkewed
         3        PentSpiralSkewed
         4        DiamondSpiral

The PyramidSpiral is a re-shaped SquareSpiral looping at the same rate.

FUNCTIONS

See "FUNCTIONS" in Math::PlanePath for behaviour common to all path classes.

$path = Math::PlanePath::SquareSpiral->new ()
$path = Math::PlanePath::SquareSpiral->new (wider => $w)

Create and return a new square spiral object. An optional wider parameter widens the spiral path, it defaults to 0 which is no widening.

($x,$y) = $path->n_to_xy ($n)

Return the X,Y coordinates of point number $n on the path.

For $n < 1 the return is an empty list, as the path starts at 1.

$n = $path->xy_to_n ($x,$y)

Return the point number for coordinates $x,$y. $x and $y are each rounded to the nearest integer, which has the effect of treating each N in the path as centred in a square of side 1, so the entire plane is covered.

FORMULAS

N to X,Y

There's a few ways to break an N into a side and offset into the side. One convenient way is to treat a loop as starting at the bottom right corner, so N=2,10,26,50,etc, If the first at N=2 is reckoned loop number d=1 then

    Nbase = 4*d^2 - 4*d + 2

For example d=3 is Nbase=4*3^2-4*3+2=26 at X=3,Y=-2. The biggest d with Nbase <= N can be found by inverting with the usual quadratic formula

    d = floor (1/2 + sqrt(N/4 - 1/4))

For Perl it's good to keep the sqrt argument an integer (when a UV integer is bigger than an NV float, and for BigRat accuracy), so rearranging

    d = floor ((1+sqrt(N-1)) / 2)

So Nbase from this d leaves a remainder which is an offset into the loop

    Nrem = N - Nbase
         = N - (4*d^2 - 4*d + 2)

The loop starts at X=d,Y=d-1 and has sides length 2d, 2d+1, 2d+1 and 2d+2,

             2d      
         +------------+        <- Y=d
         |            |
    2d   |            |  2d-1
         |     .      |
         |            |
         |            + X=d,Y=-d+1
         |
         +---------------+     <- Y=-d
             2d+1

         ^
       X=-d

The X,Y for an Nrem is then

     side      Nrem range            X,Y result
     ----      ----------            ----------
    right           Nrem <= 2d-1     X = d
                                     Y = -d+1+Nrem
    top     2d-1 <= Nrem <= 4d-1     X = d-(Nrem-(2d-1)) = 3d-1-Nrem
                                     Y = d
    left    4d-1 <= Nrem <= 6d-1     X = -d
                                     Y = d-(Nrem-(4d-1)) = 5d-1-Nrem
    bottom  6d-1 <= Nrem             X = -d+(Nrem-(6d-1)) = -7d+1+Nrem
                                     Y = -d

The corners Nrem=2d-1, Nrem=4d-1 and Nrem=6d-1 get the same result from the two sides that meet so it doesn't matter if the high comparison is "<" or "<=".

The bottom edge runs through to Nrem < 8d, but there's no need to check that since d=floor(sqrt()) above ensures Nrem is within the loop.

A small simplification can be had by subtracting an extra 4d-1 from Nrem to make negatives for the right and top sides and positives for the left and bottom.

    Nsig = N - Nbase - (4d-1)
         = N - (4*d^2 - 4*d + 2) - (4d-1)
         = N - (4*d^2 + 1)

     side      Nsig range            X,Y result
     ----      ----------            ----------
    right           Nsig <= -2d      X = d
                                     Y = d+(Nsig+2d) = 3d+Nsig
    top      -2d <= Nsig <= 0        X = -d-Nsig
                                     Y = d
    left       0 <= Nsig <= 2d       X = -d
                                     Y = d-Nsig
    bottom    2d <= Nsig             X = -d+1+(Nsig-(2d+1)) = Nsig-3d
                                     Y = -d

N to X,Y with Wider

With the wider parameter stretching the spiral loops the formulas above become

    Nbase = 4*d^2 + (-4+2w)*d + 2-w

    d = floor ((2-w + sqrt(4N + w^2 - 4)) / 4)

Notice for Nbase the w is a term 2*w*d, being an extra 2*w for each loop.

The left offset ceil(w/2) described above ("Wider") for the N=1 starting position is written here as wl, and the other half wr arises too,

    wl = ceil(w/2)
    wr = floor(w/2) = w - wl

The horizontal lengths increase by w, and positions shift by wl or wr, but the verticals are unchanged.

             2d+w      
         +------------+        <- Y=d
         |            |
    2d   |            |  2d-1
         |     .      |
         |            |
         |            + X=d+wr,Y=-d+1
         |
         +---------------+     <- Y=-d
             2d+1+w

         ^
       X=-d-wl

The Nsig formulas then have w, wl or wr variously inserted. In all cases if w=wl=wr=0 then they simplify to the plain versions.

    Nsig = N - Nbase - (4d-1+w)
         = N - ((4d + 2w)*d + 1)

     side      Nsig range            X,Y result
     ----      ----------            ----------
    right         Nsig <= -(2d+w)    X = d+wr
                                     Y = d+(Nsig+2d+w) = 3d+w+Nsig
    top      -(2d+w) <= Nsig <= 0    X = -d-wl-Nsig
                                     Y = d
    left       0 <= Nsig <= 2d       X = -d-wl
                                     Y = d-Nsig
    bottom    2d <= Nsig             X = -d+1-wl+(Nsig-(2d+1)) = Nsig-wl-3d
                                     Y = -d

OEIS

This path is in Sloane's Online Encyclopedia of Integer Sequences in various forms,

    http://oeis.org/A180714  (etc)

    A180714    X+Y coordinate sum
    A053615    abs(X-Y), distance to nearest pronic
    A079813    abs(dY), k 0s followed by k 1s
    A118175    abs(dY), initial 1 then k 0s followed by k 1s
    A063826    direction 1=right,2=up,3=left,4=down

    A033638    N positions of the turns (extra initial 1, 1)
    A172979      those positions which are primes too

    A054552    N values on X axis (East)
    A054554    N values on X=Y diagonal (NE)
    A054556    N values on Y axis (North)
    A054567    N values on negative X axis (West)
    A054569    N values on negative X=Y diagonal (SW)
    A033951    N values on negative Y axis (South)
    A053755    N values on X=-Y opp diagonal X<=0 (NW)
    A016754    N values on X=-Y opp diagonal X>=0 (SE)

    A137928    N values on X=1-Y opposite diagonal
    A002061    N values on X=Y diagonal pos and neg
    A016814    (4k+1)^2, every second N on south-east diagonal

    A053999    prime[N] on X=-Y opp diagonal X>=0 (SE)
    A054551    prime[N] on the X axis (E)
    A054553    prime[N] on the X=Y diagonal (NE)
    A054555    prime[N] on the Y axis (N)
    A054564    prime[N] on X=-Y opp diagonal X<=0 (NW)
    A054566    prime[N] on negative X axis (W)

    A068225    permutation N -> N at the right X+1,Y
    A121496      run lengths of consecutive N in that permutation
    A068226    permutation N -> N at the left X-1,Y
    A020703    permutation N by transposing X,Y

    A033952    digits on negative Y axis
    A033953    digits on negative Y axis, starting 0
    A033988    digits on negative X axis, starting 0
    A033989    digits on Y axis, starting 0
    A033990    digits on X axis, starting 0

    A062410    total sum previous row or column

See summary at

    http://oeis.org/A068225/a068225.html

SEE ALSO

Math::PlanePath, Math::PlanePath::PyramidSpiral

Math::PlanePath::DiamondSpiral, Math::PlanePath::PentSpiralSkewed, Math::PlanePath::HexSpiralSkewed, Math::PlanePath::HeptSpiralSkewed

Math::PlanePath::CretanLabyrinth

X11 cursor font "box spiral" cursor which is this style (but going clockwise).

HOME PAGE

http://user42.tuxfamily.org/math-planepath/index.html

LICENSE

Copyright 2010, 2011, 2012 Kevin Ryde

This file is part of Math-PlanePath.

Math-PlanePath is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version.

Math-PlanePath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with Math-PlanePath. If not, see <http://www.gnu.org/licenses/>.