8
3
Given a positive input number n
, construct a spiral of numbers from 1
to n^2
, with 1
in the top-left, spiraling inward clockwise. Take the sum of the diagonals (if n
is odd, the middle number n^2
is counted twice) and output that number.
Example for n = 1
:
1
(1) + (1) = 2
Example for n = 2
:
1 2
4 3
(1+3) + (4+2) = 4 + 6 = 10
Example for n = 4
:
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
(1+13+15+7) + (10+16+14+4) = 36 + 44 = 80
Example of n = 5
:
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
(1+17+25+21+9) + (13+23+25+19+5) = 73 + 85 = 158
Further rules and clarifications
- This is OEIS A059924 and there are some closed-form solutions on that page.
- The input and output can be assumed to fit in your language's native integer type.
- The input and output can be given in any convenient format.
- You can choose to either 0-index or 1-index, as I am here in my examples, for your submission. Please state which you're doing.
- Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
- If possible, please include a link to an online testing environment so other people can try out your code!
- Standard loopholes are forbidden.
- This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.
1
+3-3*(-1)^n
is not really same as6
, although the difference is lost in integer division. – fergusq – 2017-08-30T20:19:33.940@fergusq you're right, but the formula given as the expression in PARI (which I base my solution on) has
+3-3*(-1^n)
which is the same as+6
. I will update my answer to make that more obvious. – Giuseppe – 2017-08-30T20:21:45.103@Giuseppe It's
+6
ifn
is odd, but+0
whenn
is even – Bergi – 2017-08-30T22:32:16.9473@Bergi
3-3*(-1^n)
is always6
but3-3*(-1)^n
has that alternating behavior. The original formula has the latter, which makes the use of integer division unnecessary, as it is always divisible by 12 – Giuseppe – 2017-08-30T22:36:24.8101Ah, right. It's weird though that the original author overlooked this, isn't it? – Bergi – 2017-08-30T22:44:47.533
Congrats on 7k (you had 6,999 before I upvoted) – NoOneIsHere – 2017-11-20T20:50:52.113