# A spiral of numbers0519

For the past few days, I've been studying the following question on StackExchange about a spiral of integers. We are looking for a closed formula for the coordinates of the $$n$$ -th element in the following integer spiral, which expands from the origin outwards and further and further into infinity:

..  9 10 11 12
23  8  1  2 13
22  7  0  3 14
21  6  5  4 15
20 19 18 17 16

First we divide the natural numbers into the following groups:

$$G_1 = \{ 1,...,8 \}\\G_2 = \{ 9, ..., 24 \}\\G_3 = \{ 25, ... 48 \}\\...\\G_k = \left\{ (2k-1)^2, (2k+1)^2 - 1 \right\}$$

We call

$$a^2 = \left(\left \lfloor \left( \frac{\left \lfloor \sqrt{n} \right \rfloor + 1}{2} \right) \right \rfloor \cdot 2 - 1 \right)^2$$

the starting number in a group.

within a group there are four subgroups of equal size (for example for $$G_1$$ this is $$g_1 = \{1,2 \}, g_2 = \{3,4 \}, g_3 = \{5,6 \}, g_4 = \{7,8\}$$). when $$n$$ changes from one subgroup to the next, the direction on the spiral path (clockwise in our example) is changed at the same time. we obtain the current direction $$b \in \{0,1,2,3\}$$ by dividing the position $$n-a^2$$ within a group by the number of elements of a subgroup:

$$b = \left \lfloor \frac{ n - a^2 }{ \text{abs}\left( a \right) + 1 } \right \rfloor$$

Now we can determine the first element within a subgroup $$g_n$$ by adding to the initial number $$a^2$$ a multiple $$b$$ of the number $$a+1$$ of elements within a group:

$$c = a^2 + b \cdot (a+1)$$

Now we can determine by simple observation:

$$x_{right} = \left(n - c - \frac{ a + 1 }{2}+1\right),\, y_{right} = \left(\frac{ a + 1 }{2}\right) \\ x_{bottom} = \left(\frac{ a + 1 }{2}\right),\, y_{bottom} = (-1) \cdot \left( n - c - \frac{ a + 1 }{2}+1\right) \\ x_{left} = (-1) \cdot \left(n - c - \frac{ a + 1 }{2}+1\right),\, y_{left} = (-1) \cdot \left(\frac{ a + 1 }{2}\right) \\ x_{top} = (-1) \cdot \left(\frac{ a + 1 }{2}\right),\, y_{top} = \left( n - c - \frac{ a + 1 }{2}+1\right)$$

Now we want to represent $$f(n)$$ in closed representation and without case distinctions. We use the sign function, the procedure I have described here. To get a pure formula depending on $$n$$, we get:

That the whole thing really works, we see with the help of SVG.js in this little visualization:

See the Pen ulam spiral by David Vielhuber (@vielhuber) on CodePen.

The spiral is also known as Ulam's spiral and has an exciting relation to prime numbers.

Back