# Count the number of turns in an Ulam spiral

Given a number on the Ulam Spiral, I want to know how many 90° turns were taken to arrive at that number. For example, to get to the number 10, you need to turn at 2, 3, 5, and 7 for a total of four turns.

I know how to generate the sequence of numbers where the turns occur, they follow the form:

$$y = \lfloor (n+2)^2/4 \rfloor+1$$

Here $$y$$ is a turning point number on the spiral and $$n$$ is the number of turns. For the example above, if we input $$n=4$$ (for 4 turns) we get:

$$y = \lfloor (4+2)^2/4 \rfloor+1 = \lfloor 36/4 \rfloor+1 = 10$$

However, I not sure how to solve for the number of turns ($$n$$) given some $$y$$ because the $$floor()$$ function has no inverse. Any insight would be appreciated.

EDIT

After looking at John Omielan's answer I realized if you solve the even equation for $$k$$, ignore the negative solution, and round up the answer it seems to work:

$$n = \left\lceil 2\sqrt{y-1}-2\right\rceil$$ I can't proof this works for every number, but it seems promising.

• See formulas at OEIS A055086. Jul 5 at 17:45
• @BillyJoe Ah this sequence is exactly what I arrived at just shifted slightly (they have a "+1" in the square root instead of a "-1"). Good find! Jul 5 at 18:13

If $$n$$ is even, i.e., $$n = 2k$$, then
$$\left\lfloor \frac{(n+2)^2}{4} \right\rfloor + 1 = (k + 1)^2 + 1 = k^2 + 2k + 2 \tag{1}\label{eq1A}$$
However, if $$n$$ is odd, i.e., $$n = 2k + 1$$, then
\begin{equation}\begin{aligned} \left\lfloor \frac{(n+2)^2}{4} \right\rfloor + 1 & = \left\lfloor \frac{(2k + 3)^2}{4} \right\rfloor + 1 \\ & = \left\lfloor \frac{4k^2 + 12k + 9}{4} \right\rfloor + 1 \\ & = k^2 + 3k + 3 \end{aligned}\end{equation}\tag{2}\label{eq2A}
Thus, if it's known that $$y$$ is an actual turning point, we then just need to solve the quadratic equation in $$k$$ for $$y$$ being equal to either \eqref{eq1A} or \eqref{eq2A} to get which one gives an integer value for $$k$$, and then the corresponding value of $$n$$. Even if it's not certain $$y$$ is a turning point, following this procedure will at least give us the value(s) of $$n$$ that are the nearest number of turn(s).
May be, you could use $$\color{red}{\lfloor x\rfloor=x-\frac 12+\frac 1\pi \tan ^{-1}(\cot (\pi x))}$$ which would give $$y=\frac{n^2+4 n+2 } 4+\frac 1\pi \tan ^{-1}\left(\cot \left(\frac{\pi n^2}{4}\right)\right)$$ $$-\frac 12 \leq \frac 1\pi \tan ^{-1}\left(\cot \left(n^2\frac{\pi }{4}\right)\right)\leq \frac 12$$ makes probably quite good bounds.