[Question]
  [
A number spiral is an infinite grid whose upper-left square has number 1. Here are the first five layers of the spiral:
[![enter image description here](https://i.stack.imgur.com/m4ei9.png)](https://i.stack.imgur.com/m4ei9.png)
**Your task is to find out the number in row y and column x.**
---
Example:
```
Input: 2 3
Out  : 8
Input: 1 1
Out  : 1
Input: 4 2
Out  : 15
```
---
Note:
1. Any programming language is allowed.
2. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge so shortest code wins.
3. Best of Luck!
Source: <https://cses.fi/problemset/task/1071>
  
[Answer]
## C (gcc), ~~44~~ 43 bytes
```
f(x,y,z){z=x>y?x:y;z=z*z-~(z%2?y-x:x-y)-z;}
```
[Try it online!](https://tio.run/##Zc7BDoIwDAbgu0/RkJBssh0AvTAnL@LFQGY4iAQxWUfw1ecmQlzoZfu7L@0qfqsqaxXRDJmho5H6jKUuUBhp9oa/iYmzErkuNEfKjZjs/dq0hMK4A1fq0QNp2gE0SEiFO04SjgKSRC8kYDgzXBn@M19d75wiUZzXEQP/MUBKxWqm9da9hieJot/b3A97yyxFMpZTtzquL@13qs8blLI0QD5v0IFlAfLZocl@AA)
The spiral has several "arms":
```
12345
22345
33345
44445
55555
```
The position \$(x, y)\$ is located on arm \$\max(x, y)\$ (assigned to variable `z`). Then, the largest number on arm \$n\$ is \$n^2\$, which alternates between being in the bottom left and top right position on the arm. Subtracting \$x\$ from \$y\$ gives the sequence \$-n+1, -n+2, \ldots, -1, 0, 1, \ldots, n-1, n-2\$ moving along arm \$n\$, so we choose the appropriate sign based on the parity of \$n\$, adjust by \$n-1\$ to get a sequence starting at 0, and subtract this value from \$n^2\$.
Thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder) for saving a byte.
[Answer]
## Python, ~~54~~ ~~50~~ 49 bytes
```
def f(a,b):M=max(a,b);return(a-b)*(-1)**M+M*M-M+1
```
-4 bytes thanks to @ChasBrown
-1 bytes thanks to @Shaggy
[Try it Online!](https://tio.run/##VYxBCoMwFETX9RTZ5Sd@hcRCwWJvkBOIYKSmVWiUNIKePtUUCt0Mj2HezJt/TlaGcO8NMaCxY6WqXnqNeHW9X5wFnXWMQyYY5ypVXGUqFcFMjqy4kcGSupZYNFgLFHueUe4p8dw0ZXKa3WA9gX3JkFY3iiZyEvsknhwXTttHDwIv7OdQmo/TYKH9Gm3uxuXtoWDksLZ/i4UP)
First time golfing! I'm more than aware this is not optimal, but whatever.
Essentially runs on the same principle as @Doorknob C code.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 15 bytes
```
X>ttq*QwoEqGd*+
```
[Try it online!](https://tio.run/##y00syfn/P8KupKRQK7A837XQPUVL@///aBMdBaNYAA "MATL – Try It Online")  
[Collect and print as a matrix](https://tio.run/##y00syflvaGBVEqWlqOQQ4fk/wq6kpFArsDzftdAzRUv7f2yZoUGq4n8A "MATL – Try It Online")
### How?
*Edit: Same technique as @Doorknob's answer, just arrived at differently.*
The difference between the diagonal elements of the spiral is the arithmetic sequence \$ 0, 2, 4, 6, 8, \ldots \$. Sum of \$ n \$ terms of this is \$ n(n - 1) \$ (by the usual AP formula). This sum, incremented by 1, gives the diagonal element at position \$ (n, n) \$. 
Given \$ (x, y) \$, we find the maximum of these two, which is the "layer" of the spiral that this point belongs to. Then, we find the diagonal value of that layer as \$ v = n(n-1) + 1 \$. For even layers, the value at \$ (x, y) \$ is then \$ v + x - y \$, for odd layers \$ v - x + y \$. 
```
X>        % Get the maximum of the input coordinates, say n
ttq*      % Duplicate that and multiply by n-1
Q         % Add 1 to that. This is the diagonal value v at layer n
wo        % Bring the original n on top and check if it's odd (1 or 0)
Eq        % Change 1 or 0 to 1 or -1
Gd        % Push input (x, y) again, get y - x
*         % Multiply by 1 or -1
          % For odd layers, no change. For even layers, y-x becomes x-y
+         % Add that to the diagonal value v
          % Implicit output
```
---
**Alternate 21 byte solution:**
```
Pdt|Gs+ttqq*4/QJb^b*+
```
[Try it online!](https://tio.run/##y00syfn/PyClpMa9WLukpLBQy0Q/0CspLklL@///aBMdBaNYAA "MATL – Try It Online")  
[Collect and print as a matrix](https://tio.run/##y00syflvaGBVEqWlqOQQ4fk/IKWkxrNYu6SksFDLRD/QKykuSUv7f2yZoUGq4n8A "MATL – Try It Online")  
From the above, we know that the function we want is 
$$ f = m \* (m - 1) + 1 + (-1)^m \* (x - y) $$
where \$ m = max(x, y) \$. 
Some basic calculation will show that one expression for max of two numbers is
$$ m = max(x, y) = \frac{x + y + abs(x - y)}{2} $$
Plugging one into another, we [find](https://www.wolframalpha.com/input/?i=f%20%3D%20m%20*%20(m%20-%201)%20%2B%201%20%2B%20(-1)%5Em%20*%20(x%20-%20y)%20where%20m%20%3D%20(x%20%2B%20y%20%2B%20abs(x-y))%2F2) that one alternate form for \$ f \$ is:
$$ f = (x-y)\cdot i^{k} + \frac{1}{4}((k-2)\cdot k) + 1 $$
where \$ k = abs(x-y) + x + y \$.
This is the function the solution implements. 
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~16~~ ~~14~~ 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
(Originally) Adapted from [Doorknob's solution](https://codegolf.stackexchange.com/a/170795/58974) over a few beers.
```
wV
nU²ÒNra
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=d1YKblWy0k5yYQ&input=OAo4)
```
wV\nnU²ÒNra     :Implicit input of integers N=[U=y, V=X]
wV              :Maximum of U & V
  \n            :Reassign to U, leaving the value in N unchanged
    n           :Subtract U from
     U²         :  U squared
       Ò        :  Subtract the bitwise NOT of
        Nr      :  N reduced by
          a     :    Absolute difference
```
[Answer]
# Pyth, 20 bytes
```
A~Qh.MZQh-+*-GH^_1Q*
```
[Test suite](http://pyth.herokuapp.com/?code=A%7EQh.MZQh-%2B%2a-GH%5E_1Q%2a&test_suite=1&test_suite_input=2%2C3%0A1%2C1%0A4%2C2&debug=0)
An almost literal translation of [Rushabh Mehta](https://codegolf.stackexchange.com/users/82007/rushabh-mehta)['s answer](https://codegolf.stackexchange.com/questions/170794/number-spiral-problem/170814#170814).
Explanation:
```
A~Qh.MZQh-+*-GH^_1Q*    | Full code
A~Qh.MZQh-+*-GH^_1Q*QQQ | Code with implicit variables filled
                        | Assign Q as the evaluated input (implicit)
A                       | Assign [G,H] as
 ~Q                     |  Q, then assign Q as
   h.MZQ                |   Q's maximal value.
                        | Print (implicit)
        h-+*-GH^_1Q*QQQ |  (G-H)*(-1)^Q+Q*Q-Q+1
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
»Ḃ-*×_‘+»×’$¥
```
[Try it online!](https://tio.run/##y0rNyan8///Q7oc7mnS1Dk@Pf9QwQ/vQ7sPTHzXMVDm09P/h5fqPmta4//8fHW2oo2AYq6MQbaSjYAyiTXQUjGJjAQ "Jelly – Try It Online")
Uses [Doorknob's method](https://codegolf.stackexchange.com/a/170795/59487). Way too long.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 12 bytes
```
ṀḂḤ’×I+²_’ṀƲ
```
[Try it online!](https://tio.run/##y0rNyan8///hzoaHO5oe7ljyqGHm4eme2oc2xQNZQNFjm/7//2@iYwQA "Jelly – Try It Online")
Computes the diagonal term with `²_’Ṁ` and adds/subtracts to the correct index value with `ṀḂḤ’×I`.
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 76 bytes
```
((({}<>))<>[(({}))]<{({}[()])<>}>)<>{}((){({}[()])({})<><([{}])><>}{}<>{}<>)
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/X0NDo7rWxk5T08YuGsTU1Iy1qQbS0RqasUCxWjsgUV2roaEJFwQpsrGz0Yiuro3VtAMqAekHm/H/v4mCEQA "Brain-Flak – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~12~~ 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ZÐ<*>ŠGR}¥+
```
-1 byte thanks to *@Emigna* changing `Èi` to `G`.
Port of [*@sundar*'s MATL answer](https://codegolf.stackexchange.com/a/170815/52210), so make sure to upvote him!
[Try it online](https://tio.run/##yy9OTMpM/f8/6vAEGy27owvcg2oPLdX@/z/aRMcoFgA) or [verify all test cases](https://tio.run/##yy9OTMpM/W/m5nl4gr2SwqO2SQpK9v@jDk@w0bI7usA9qPbQUu3/Ov@jjXSMY7miDXUMgaSJjhGYNAGSpjqmYLZpLAA).
**Explanation:**
```
Z              # Get the maximum of the (implicit) input-coordinate
               #  i.e. [4,5] → 5
 Ð             # Triplicate this maximum
  <            # Decrease it by 1
               #  i.e. 5 - 1 → 4
   *           # Multiply it
               #  i.e. 5 * 4 → 20
    >          # Increase it by 1
               #  i.e. 20 + 1 → 21
     Š         # Triple swap the top threes values on the stack (a,b,c to c,a,b)
               #  i.e. [4,5], 5, 21 → 21, [4,5], 5
      G }      # Loop n amount of times
       R       #  Reverse the input-coordinate each iteration
               #   i.e. 5 and [4,5] → [5,4]→[4,5]→[5,4]→[4,5] → [5,4]
         ¥     # Calculate the delta of the coordinate
               #  [5,4] → [1]
          +    # And add it to the earlier calculate value (output the result implicitly)
               #  21 + [1] → [22]
```
[Answer]
# [Pascal (FPC)](https://www.freepascal.org/), 90 bytes
```
uses math;var x,y,z:word;begin read(x,y);z:=max(x,y);write(z*z-z+1+(1and z*2-1)*(y-x))end.
```
[Try it online!](https://tio.run/##JchLDoMgEADQq8ySj5hQu5L0MKOMlUSpAVtxLo8m3b28DfOIi5m2sdZvpgwr7rP7YYLSnA33xyd5N9A7REiEXtwrHfevFcvfRwo7CVZsWFstLEYPrB7GSiVOU6Sk6NtaO3he "Pascal (FPC) – Try It Online")
Port of [Doorknob's answer](https://codegolf.stackexchange.com/a/170795/60517), but [sundar's answer](https://codegolf.stackexchange.com/a/170815/60517) gave me idea for `z mod 2*2-1` which I transformed into `1and z*2-1` to remove space.
[Answer]
# Mathematica 34 bytes
```
x = {5, 8};
```
so:
```
m = Max[x];
Subtract @@ x (-1)^m + m^2 - m + 1
```
(\*
54
\*)
[Answer]
# [Julia 1.0](http://julialang.org/), 35 bytes
```
x\y=(m=max(x,y))*~-m+1+(-1)^m*(x-y)
```
[Try it online!](https://tio.run/##PY2xCoMwFAD3fMXD6cVG6LOdBKfObt2MhaAWUkyUJEKy9NfTFtpuB8dxj33RimLOUaYWTWtUxCgS5@WzMgc6YEX8ZkqMVeJ5c9qGxWJxnX2AUfnZNwVnRm34VQL6Wp4EkCQBZ1kPnLF/dVmtD24fwzyBUcHp@Kk7aKF/3@G@OoigLVBDRwHphwObtN8WlbDjLL8A "Julia 1.0 – Try It Online")
[Answer]
# JavaScript (ES6), 46 bytes
```
f=(r,c,x)=>r<c?f(c,r,1):r%2-!x?r*r-c+1:--r*r+c
```
[Answer]
# [Java (JDK 10)](http://jdk.java.net/), 39 bytes
```
x->y->(y-x)*((y=x>y?x:y)%2*2-1)+y*y-y+1
```
[Try it online!](https://tio.run/##TZAxa8MwEIX3/IojEJAc2dRup6R26VLoUDqETsGD6thBqSMb6Rx0BP92V7Hd0EGne@@O78Gd5EWGp8PPoM5tYxBOXkcdqjqqOl2ganQUbBdt912rAopaWgsfUmm4LgBm16JE/10adYCzn7EdGqWP@xykOVo@rgK8a3ybic@@/9LS0GdbGomNyaCCdHBhRmHGKHQ8YIxSl9GL2xBfJUESxnxNAYW0joftyFMa97nPwNKihXROAbhCIuARenHXsYD4v34SkNx1P9GqxgAbkSNwM2H5nepH4HzKzd4/5ALoT8T5dt7ZkcXyHDUdRq0/AFZs6dLVwe@O1ZS2q9G3K70U4LwtoIpk29bEHJ@aV@tPw4jzidkvbq8ffgE "Java (JDK 10) – Try It Online")
## Credits
* Port of [Doorknob's answer](https://codegolf.stackexchange.com/a/170795/16236).
[Answer]
# [Rockstar](https://codewithrockstar.com/), ~~127~~ ~~118~~ 115 bytes
[Also](https://codegolf.stackexchange.com/a/170823/58974) adapted from [Doorknob's solution](https://codegolf.stackexchange.com/a/170795/58974).
```
listen to Y
listen to X
let M be Y is less than X and X-0 or Y-0
let R be M*M-M
let R be-M-Y and Y-X or X-Y
say R+1
```
[Try it here](https://codewithrockstar.com/online) (Code will need to be pasted in, with each input integer on an individual line)
]