[Question]
  [
If we take the natural numbers and roll them up counter clock-wise into a spiral we end up with the following infinite spiral:
```
                  ....--57--56
                             |
36--35--34--33--32--31--30  55
 |                       |   |
37  16--15--14--13--12  29  54
 |   |               |   |   |
38  17   4---3---2  11  28  53
 |   |   |       |   |   |   |
39  18   5   0---1  10  27  52
 |   |   |           |   |   |
40  19   6---7---8---9  26  51
 |   |                   |   |
41  20--21--22--23--24--25  50
 |                           |
42--43--44--45--46--47--48--49
```
Given some number in that spiral your task is to determine its neighbours - meaning the element above, left, right and below it.
### Example
If we have a look at `27` we can see that it has the following neighbours:
* above: `28`
* left: `10`
* right: `52`
* below: `26`
So the output would be: `[28,10,52,26]`
### Rules
* Input will be a number \$n \geq 0\$ in any [default I/O format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods)
* Output will be a list/matrix/.. of that numbers' 4 neighbours in any (consistent!) order
* You may work with a spiral that starts with 1 instead of 0, however you should specify that in your answer
### Examples
The output is in the format `[above,left,right,below]` and uses a 0-based spiral:
```
0  ->  [3,5,1,7]
1  ->  [2,0,10,8]
2  ->  [13,3,11,1]
3  ->  [14,4,2,0]
6  ->  [5,19,7,21]
16  ->  [35,37,15,17]
25  ->  [26,24,50,48]
27  ->  [28,10,52,26]
73  ->  [42,72,74,112]
101  ->  [100,146,64,102]
2000  ->  [1825,1999,2001,2183]
1000000  ->  [1004003,1004005,999999,1000001]
```
  
[Answer]
# [R](https://www.r-project.org/), 156 bytes
```
function(n){g=function(h)c(0,cumsum(h((4*(0:(n+2)^2)+1)^.5%%4%/%1/2)))
x=g(sinpi)
y=g(cospi)
a=x[n]
b=y[n]
which(x==a&(y==b+1|y==b-1)|y==b&(x==a+1|x==a-1))}
```
[Try it online!](https://tio.run/##bZNtc5swDMff8ym09tKzF6W1DYSkNz5JL70DYgJrgjswedjTV89kZ23Dho87Gfknyfoj2nOZnsu@KWxtGtbwH5v0/a3iBRNY9Luu37GKsegzE4@smSr@rPhU8uf7eDKJJg8T@aA458Ex3bCubl5rHpxoW5jObbP0@NSsgjw9OXOo6qJixzTN7tgpTfOp/OnMTHJv7/wROZ0hJ/91voW3C4E1UJhmr1vrtmKWZ51eQ92Aade69ceVLl7gUNsKbKXB6s5CQVQXfNet8XwJX2bvKdkLL9kL9TKTwRXCBIfLugV9fNWF1etHeAoxRonJ6pqUo6RCgVLgYoCqUVSGGKKUKAdsOM5GGCHlHqDzUZRuusQE1TCtfIOHfcUYJigpZNibisdoNUcVYSww@qe9ZJReOCFihWo@oJNwjI4UJvREJIgaXlz8FXqohyCZoznOKUAMA5QQl484DFgoJ8xyiXQuSZ1FuAqCW@ib0rS2bzKrtyc/OtuMRsfPT6u/9XWrOzdf2XZrCoIggz3lNDR0VWahdocG8noDpfdp6HRLgwrsd3IfwyYHU0Kb7T5xKpbrIus77fJ1FZXVjY8ozFrDQX/U2JlWwz7b9q52lTXQaL3W63tKQaH@braqO4SvvRtzIjb6I1NeW7i5@mFvXNDFQT/uNPI@1/tAZb/4fypHQtCQehvj0i@8wHJ1/gM "R – Try It Online")
* posted another R answer since it's a slightly different approach than @ngn
* 1-indexed
* neighbours are always sorted by ascending value
* saved 6 bytes removing `round` and using `cospi(x)/sinpi(x)` which are more precise than `cos(x*pi)/sin(x*pi)` in case of half numbers (`0.5`, `1.5` etc...)
* saved another byte removing the minus on y coordinates since the result is the same (just up/down neighbours are reversed)
---
## **Explanation :**
If we look at the matrix coordinates of the values, considering the first value `0` placed at `x=0, y=0`, they are :
```
x = [0,  1,  1,  0, -1, -1, -1,  0,  1,  2,  2,  2,  2,  1,  0, ...] 
y = [0,  0,  1,  1,  1,  0, -1, -1, -1, -1,  0,  1,  2,  2,  2, ...]
```
The `x` coordinates follow the [A174344 OEIS sequence](https://oeis.org/A174344) with the recursive formula : 
```
a(1) = 0, a(n) = a(n-1) + sin(mod(floor(sqrt(4*(n-2)+1)),4)*pi/2)
```
The same formula holds for `y` matrix coordinates, but with `cos` instead of `sin` and negated :
```
a(1) = 0, a(n) = a(n-1) - cos(mod(floor(sqrt(4*(n-2)+1)),4)*pi/2)
```
So, in R we can translate the formula to this function, taking `sinpi/cospi` as parameter :
```
g=function(h)c(0,cumsum(h((4*(0:(n+2)^2)+1)^.5%%4%/%1/2)))
```
and we generate the two coordinates vectors (we don't negate the y coords since we'll get the same result, just with up/down neighbours reversed) :
```
x=g(sinpi)
y=g(cospi)
```
Note that we have generated `(n+2)^2` coordinates, which are more than the minimum necessary coordinates containing both `n` and their neighbours (a tighter bound would be `(floor(sqrt(n))+2)^2` but unfortunately is less "golfy").
Therefore, now that we have all the coordinates, we first search the coordinates `a,b` corresponding to our `n` : 
```
a=x[n]
b=y[n]
```
finally we select the positions of their neighbours, i.e. : 
* the up/down neighbours `where x == a and y == b+1 or b-1`
* the right/left neighbours `where y == b and x == a+1 or a-1`
using :
```
which(x==a&(y==b+1|y==b-1)|y==b&(x==a+1|x==a-1))
```
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 238 bytes
```
((){[()]<((({}[((()))]<>)<<>{((([{}]({}))([{}]{})())[()]){({}[()])<>}{}}>)<<>({}<(((({}{})()){}<>({}))()())<>>)<>>()())<>{{}((()()()[({})]){}<>({}<{}>))(<>)}>}{}){<>((((())()())()())()())(<>)}{}{({}[()]<<>({}<>)<>({}<({}<({}<>)>)>)<>>)}<>
```
[Try it online!](https://tio.run/##TU7BCkIxDPud5iAMz6M/MnZ4HgRRPHgt/faZ9E2Q0i1p06a3z/F4X@6v47mWGWIYZjezyMEXIHP07kE2IicbQCEC9qVHlJyge0ZmDbCkPfxOIamfw2LdXblxRMpMMaSZP3UPLoPxhNRmBKtWd9Xk3yMJrfYh218edcdOh0LexGtdW2tf "Brain-Flak – Try It Online")
Output is in the order left, up, right, down.
### Explanation
```
# If n is nonzero:
((){[()]<
  ((
    # Push 1 twice, and push n-1 onto other stack.
    ({}[((()))]<>)
    # Determine how many times spiral turns up to n, and whether we are on a corner.
    # This is like the standard modulus algorithm, but the "modulus" used
    # increases as 1, 1, 2, 2, 3, 3, ...
    <<>{((([{}]({}))([{}]{})())[()]){({}[()])<>}{}}>
  # Push n-1: this is the number behind n in the spiral.
  )<
    # While maintaining the "modulus" part of the result:
    <>({}<
      # Push n+2k+1 and n+2k+3 on top of n-1, where k is 3 more than the number of turns.
      # n+2k+1 is always the number to the right in the direction travelled.
      # If we are on a corner, n+2k+3 is the number straight ahead.
      (((({}{})()){}<>({}))()())<>
    >)<>
  # Push n+1.  If we are on a corner, we now have left, front, right, and back
  # on the stack (from top to bottom)
  >()())
  # If not on a corner:
  <>{{}
    # Remove n+2k+3 from the stack entirely, and push 6-2k+(n+1) on top of the stack.
    ((()()()[({})]){}<>({}<{}>))
  (<>)}
>}{})
# If n was zero instead:
{
  # Push 1, 3, 5, 7 on right stack, and implicitly use 1 (from if/else code) as k.
  <>((((())()())()())()())
(<>)}{}
# Roll stack k times to move to an absolute reference frame
# (switching which stack we're on each time for convenience)
{({}[()]<<>({}<>)<>({}<({}<({}<>)>)>)<>>)}<>
```
[Answer]
# [~~Perl 6~~Raku](http://raku.org/), ~~94~~ ~~83~~ 78 bytes
~~{my \s=0,|[+] flat((1,*i...*)Zxx flat(1..Inf Z 1..Inf));map {first :k,s[$\_]+$^d,s},i,-1,1,-i}~~
~~{my \s=0,|[+] flat((1,*i...*)Zxx(1,1.5...\*));map {first :k,s[$\_]+$^d,s},i,-1,1,-i}~~
```
{my \s=0,|[\+] flat (1,*i...*)Zxx(1,3/2...*);(grep :k,1==(s[$_]-*).abs,s)[^4]}
```
[Try it online!](https://tio.run/##HYnhCoIwGEVf5SIjpn2tbZZCsR4kNTFwERmJ64diPvta/Thwzr19O3SZf05YWRg/BymdkfQpynUF2zVvcEXJXQiRxOdxDJFu9b@O/Da0PQ4PUsZwV7C62iSxaK6OXFxcdtXiXTMhYjXMCbMFq5cI9jVAEhRBE1JCFjyg94GckIdJyd8rpfRf "Perl 6 – Try It Online")
`s` is a lazy, infinite list of spiral coordinates, represented as complex numbers. It's constructed from two other infinite lists: `1, *i ... *` makes the list `1, i, -1, -i ...`. `1, 1.5 ... *` makes the list `1, 1.5, 2, 2.5, 3, 3.5 ...`. Zipping these two lists together with list replication produces the list of steps from each spiral coordinate to the next: `1, i, -1, -1, -i, -i, 1, 1, 1, i, i, i ...`. (The fractional parts of the right-hand arguments to the list replication operator are discarded.) Doing a triangular addition reduction (`[\+]`) on this list (and pasting 0 onto the front) produces the list of spiral coordinates.
~~Finally, starting from the complex number `s[$_]` (`$_` being the sole argument to the function), we look up the indexes (`first :k`) in the spiral of the complex numbers which are offset from that number by `i`, `-1`, `1`, and `-i`.~~
I shaved a few bytes off by searching for the matching elements in index order, and by testing that the absolute value of the complex difference between the coordinates is 1, rather than testing for 1, -1, i, and -1 explicitly.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 15 bytes
```
2+1YLtG=1Y6Z+g)
```
Input and output are 1-based.
The output gives the left, down, up and right neighbours in that order.
[Try it online!](https://tio.run/##y00syfn/30jbMNKnxN3WMNIsSjtd8/9/QwA) Or [verify all test cases](https://tio.run/##FY1NC4JAFEX371fcFi3CiGYSbdMuCKRlQbbqqWMOqDPMR@GvN9veczh34NDPr0cBYA09tnrUQaE3xu5w9wp1r21l2DUoFuyDU9zAtLjMMhHlNRQnUWbP5L2ZP6vz7R9RXHcwMdgYoD18Z74j2KM10WGMQ6XcsirLjoNqUE3wlmvVbBfDLX/sdJhmQZIOlFJOIieZkTxSnpLYyx8) except the last two, which time out on TIO.
```
2+      % Implicit input: n. Add 2. This is needed so that
        % the spiral is big enough
1YL     % Spiral with side n+2. Gives a square matrix
t       % Duplicate
G=      % Compare with n, element-wise. Gives 1 for entry containing n
1Y6     % Push 3×3 mask with 4-neighbourhood
Z+      % 2D convolution, keeping size. Gives 1 for neighbours of the
        % entry that contained n
g       % Convert to logical, to be used as an index
)       % Index into copy of the spiral. Implicit display
```
[Answer]
# [R](https://www.r-project.org/), 172 bytes
```
function(x,n=2*x+3,i=cumsum(rep(rep(c(1,n,-1,-n),l=2*n-1),n-seq(2*n-1)%/%2))){F[i]=n^2-1:n^2
m=matrix(F,n,n,T)
j=which(m==x,T)
c(m[j[1],j[2]+c(-1,1)],m[j[1]+c(-1,1),j[2]])}
```
[Try it online!](https://tio.run/##NY3LCsIwEEX3/Qo3hRk7QZOiCzHbfoG7EEFCS1PMqH1gQfz22Acu5sCZuZdpY7U5i1gN7Hr/YBiJtdqOWU5euyF0Q4C2fC7jQBKTkCQY6T6lWEgkFl35glXSXaoQ8VMYbzVflZCniUnQ4da3foRi6jNdMGn0u/auhqD1OLuDYBojLTVG2czB9ESipXX59@Vo8Rsr2GNSgZyhZuSLHhc/YPwB "R – Try It Online")
This is R, so obviously the answer is 0-indexed.
Most of the work is creating the matrix. Code inspired by: <https://rosettacode.org/wiki/Spiral_matrix#R>
[Answer]
# [JavaScript (V8)](https://v8.dev/), ~~165 162~~ 151 bytes
Prints the indices.
```
f=(n,x=w=y=n+2)=>y+w&&[-1,0,1,2].map(d=>(g=(x,y)=>(k=2*Math.max(x,-x,y,-y))*k+(k+x+y)*(y>=x||-1))(x+d%2,y+~-d%2)-n||print(g(x,y)))|f(n,x+w?x-1:(y--,w))
```
[Try it online!](https://tio.run/##TY5NT8MwDIbv/ApfWO3GqZYgPrQp5cSRXzDtUHW0Gx1p1VVrIgJ/vRhOHF5/PH5l@726Vpd6PA2Tvj4tS@PQc3Czi84rS66Mal6tdtrwmg3bffFRDXhwJbYOA0cxYOds/lpNRxkFYVow60iUdwo7FVSkHGPpQkraEGFQh1vLUX1ryaR9SsN48hO2f/uIUvP7gZqfgzYbjFrzTLRsd2sGw2AZ7hgepBbZe9Hj/qZo@vGlqo/owZXwCXXvL/35rTj3LWbCIAMFXpRtMtqCHJD43yTtFy0/ "JavaScript (V8) – Try It Online")
### How?
For \$x, y \in \mathbb{Z}\$, we compute the 0-based index \$I\_{x,y}\$ of the spiral with:
$$A\_{x,y}=2\cdot\max(|x|,|y|)$$
$$S\_{x,y}=\begin{cases}1,&\text{if }y\ge x\\-1,&\text{if }y<x\end{cases}$$
$$I\_{x,y}=A\_{x,y}^2+(A\_{x,y}+x+y)\times S\_{x,y}$$
*Adapted from [this answer](https://math.stackexchange.com/a/2639611) from math.stackexchange.*  
*Also used in [Can you make your way through the Ulam spiral?](https://codegolf.stackexchange.com/a/216328/58563)*  
*Saved 1 byte thanks to [@att](https://codegolf.stackexchange.com/users/81203/att).*
[Answer]
# [Python 2](https://docs.python.org/2/), ~~177~~ ~~164~~ 1~~46~~ 144 bytes
```
def f(n):N=int(n**.5);S=N*N;K=S+N;F=4*N;return[n+[F+3,[-1,1-F][n>K]][n>S],n+[F+5,-1][n>K],n+[[1,3-F][n<K],-1][0<n==S],n+[F+7,1][n<K]][::1-N%2*2]
```
[Try it online!](https://tio.run/##NZFNb8IwDIbP41dkh6kfuFOdprQUypELUi89RrmNalwCqhjSLvz17nXCosSyn9ex3eb2e/@@er0sX@dJTanPuqG/@Hvq8/yzznZjP@TD7tSP62F37A38@Xz/mb31a3tcV2QLJi6OzvrDyYkdHQWppoIjldgyVSFrj1iEcu/7/j@3IY6Ss13HxfChc@2W6TorTw918crakpStSNWkmFTjHEI4VpOCwjhtYFo48rAZOgdYCTSksCU/sA2OFNuiGnBMZKEVcAXGIsdOuhYDUaNEjWbm1a0R08YBatTWm8Ab6WgQN3KMzKJjg5KDlZkN6m1EK6OmS8GWWx3m2mIyIJbh2up1O6zombKUjwwOLmzDCgALn@O61dttxkviHybFISF5W0qez2eSp4/3XsJsFTOm1GTLHw "Python 2 – Try It Online")
Calculates `u,l,r,d` directly from `n`.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~66~~ 60 bytes
```
{(⊃⍸⍵=s)⌷{⊢/4 2⍴⍵}⌺3 3⊢s←{⌽⍉⍵⍪⍨⌽(⍳(⌈/⍴⍵)+⌈/,⍵)~,⍵}⍣(⍵+4)⊢⍪1}
```
[Try it online!](https://tio.run/##JY29DgFxEMR7T7HlXe7E/@NQqTS0zgtcIqeRkKjkQiMR5FYolBoaEYkCIRKNR5kXOetssZmdzG82GvSKnVHU63ezLHGwnIKf4Htt6CJ9JFjuSwEZ8E28MdKXJSveELN1gvQNXogPPoGPcjrgq4N0XvrnXe@n/Z@a@DnPB4ncvcCVDqH0OIulCbzK/54F@1wsZhustmGrLrvdaIaZJOPPUXuKNBmyVCFdIVMmU6WqJa10AbyLySil/kqrfL4 "APL (Dyalog Unicode) – Try It Online")
1-indexed.
I'd been wanting to solve spiral challenges in APL for a while, so I figured I'd make a spiral creating function for this. I've used simple array magic to make it(and ngn will probably find an insane math relation to calculate it, most likely).
[-6 bytes](https://chat.stackexchange.com/transcript/message/56428225#56428225) from Adám.
## Explanation
```
{(⊃⍸⍵=s)⌷{⊢/4 2⍴⍵}⌺3 3⊢s←{⌽⍉⍵⍪⍨⌽(⍳(⌈/⍴⍵)+⌈/,⍵)~,⍵}⍣(⍵+4)⊢⍪1} input → n
                                                         ⍪1  to [[1]],
                                                  ⍣(⍵+4)⊢    apply the following n+4 times:
                                (⍳(⌈/⍴⍵)+⌈/,⍵)               range 1..max(i)+max(shape(i))
                                              ~,⍵            without i
                            ⍵⍪⍨                              add that as a row
                          ⌽⍉                                 rotate 90 degrees clockwise
                       s←                                    assign the spiral to s
         {       }⌺3 3⊢                                      to the 3x3 paritions of the spiral:
          ⊢/4 2⍴⍵                                            get every 2nd element   
 ⊃⍸⍵=s                                                       find indices of n in the spiral                
(     )⌷                                                     and index into the matrix of neighbours 
```
[Answer]
# [PHP](http://www.php.net/) (>=5.4), 208 bytes
```
<?$n=$argv[1];for(;$i++<($c=ceil(sqrt($n))+($c%2?2:3))**2;$i!=$n?:$x=-$v,$i!=$n?:$y=+$h,${hv[$m&1]}+=$m&2?-1:1,$k++<$p?:$p+=$m++%2+$k=0)$r[-$v][+$h]=$i;foreach([0,1,0,-1]as$k=>$i)echo$r[$x+$i][$y+~-$k%2].' ';
```
To run it:
```
php -n -d error_reporting=0 <filename> <n>
```
Example:
```
php -n -d error_reporting=0 spiral_neighbourhoods.php 2001
```
Or [Try it online!](https://tio.run/##PY5Ra8MgAIT/SgeXNVYdat@S2vwQkRGyrJFsak0ILWP76XP2ZU/HHd8dF6eY86mD1@jTZTPStu8h1S0cpacagx5G91Ev17TW8ITQElWqU82RkMNBFexJw3cNbppjY//2rikmhq9pM/h8lvab6qKq47KRDHPZRixYfMSUVopi1oIgmbJiTelaDfd4MvbDVBvBJBOMS9svBTzDkXGYQsFxo3DW4E5/OOZK2Zf9bt/mnJUQ8jfE1QW/ZO4zf9uNKYX0msYY0ur8RYs/ "PHP – Try It Online")
**Notes:**
* The `-d error_reporting=0` option is used to not output notices/warnings.
* This spiral starts with 1.
---
# How?
I'm generating the spiral with a modified version of [this answer](https://codegolf.stackexchange.com/a/126122/81663) in a 2 dimensional array.
I decide on the size of the spiral based on the input `n` with a formula to always get an extra round of numbers in the spiral (guarantee for existence of above/below/left/right). An extra round of numbers means `+2` in height and `+2` in width of the 2 dimensional array.
So if `n` will be located in a spiral with maximum size of `3*3`, then generated spiral will be `5*5`.
Spiral size is `c*c` where `c = ceil(sqrt(n)) + k`, if `ceil(sqrt(n))` is odd, then `k` is 2 and if `ceil(sqrt(n))` is even, then `k` is 3.
For example, the above formula will result in this:
* If `n = 1` then `c = 3` and spiral size will be `3*3`
* If `n <= 9` then `c = 5` and spiral size will be `5*5`
* If `n <= 25` then `c = 7` and spiral size will be `7*7`
* If `n <= 49` then `c = 9` and spiral size will be `9*9`
* And so on ...
While generating the spiral, I store the `x` and `y` of `n` and after generation, I output the elements above/below/left/right of it.
]