Having the number 59 for example find $x$ which $x^2$ is closer but lower to the 59. In this case is 7

110 Views Asked by At

I don't know how to name this but this is what I would need.

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

This is a map of blocks. It starts by 0 and the go 1, 2, 3, 4, 5.... circular clockwise. So given that I know the number 52, in this case I would like to know it's $(x, y)$, which in this case is $(x=4,\ y=0)$.

The first thing I need is:

  • Having the number 59 for example find $x$ which $x^2$ is closer but lower to the 59. In this case is 7.

Which gives me the magnitude, to know how away from 0 is, then based on that I have the length of the square, this means how many blocks are on each side. In the case of 52, I get the number 7 based on that: $52-49+1 = 4$. With the 4 then I will make a loop until it finds the position. It will turn after 8 times.

Any help is appreciated, thanks very much!

3

There are 3 best solutions below

3
On

This type of construction is known as an Ulam spiral, so you might want to search for that. It has connections to prime numbers. For example, diagonals on the spiral correspond to quadratic polynomials. The youtube channel Numberphile has a great video on this subject.

8
On

You work by taking it apart. I will use $n$ for the number you are looking for the position of, as you use $x,y$ as the coordinates. As you say, you first want to find $m=\lfloor \sqrt n \rfloor$, the greatest integer less than or equal to the square root of $n$, as $m^2$ is the last upper right or lower left corner before $n$

If $m$ is even, its coordinates are $(-\frac m2,-\frac m2)$. Now you need to count $n-m^2$ spaces beyond. If $n \le m^2+m+1$, it is in the column just to the left of $m^2$ and its coordinates are $(-\frac m2-1,-\frac m2+n-m^2-1)$...

If $m$ is odd, its coordinates are $(\frac {m+1}2,\frac {m+1}2-1)$...

The ...s have more reasoning like the second sentence of the second paragraph. I leave that as an exercise.

2
On

After hard work I've been able to create a not efficient algorithm checkout here the code and comments