Find the nth cross-alternate sum
Jelly, 21 19 11 10 7 bytes
²~³¡H+2
Try it online!
Idea
Assume for a second that the first term of the final sum is subtracted rather than added.
Let n be a positive integer.
Even case
1 6
8 11
15 16
21 22
26 29
31 36
The differences between the diagonal elements on the lower half of the rows are the first n ÷ 2 odd natural numbers. Since 1 + 3 + 5 + … + (2k + 1) = k2, they sum to (n ÷ 2)2 = n2 ÷ 4.
In this example
- 1 + 6 - 8 + 11 - 15 + 16 - 21 + 22 - 26 + 29 - 31 + 36 =
-(1 - 6)-(8 - 11)-(15 - 16)-(21 - 22)-(26 - 29)-(31 - 36) =
( 5 + 3 + 1 )+( 1 + 3 + 5 ) =
9 + 9 = 18
Thus, the sum is 2 × n2 ÷ 4 = n2 ÷ 2.
Odd case
1 5
7 9
13
17 19
21 25
The differences between the diagonal elements on the corresponding rows from above and below (1
and 5
, and 21
and 25
; 7
and 9
, and 17
and 19
) is the same, so they will cancel out in the alternating sum.
In this example
- 1 + 5 - 7 + 9 - 13 + 17 - 19 + 21 - 25 =
-(1 - 5)-(7 - 9)- 13 +(17 - 19)+(21 - 25) =
4 + 2 - 13 - 2 - 4 = -13
All that's left is the negative of the central element, which is the arithmetic mean of the first and last number, so it can be calculated as -(n2 + 1) ÷ 2.
General case
Since ~x = -(x + 1) for two's complement integers (~ denotes bitwise NOT), the formula for the odd case can be rewritten as ~n2 ÷ 2.
Also, since the first term (1) of the original sum is added instead of subtracted, the above formulas leave an error of 2, which has to be corrected.
Therefore, the nth cross-alternate sum is n2 ÷ 2 + 2 if n is even, and ~n2 ÷ 2 + 2 if it is odd.
Finally, bitwise NOT is an involution, i.e., ~~x = x for all x. This way ~~~x = ~x, ~~~~x = x, and, in general, ~nx (meaning that ~ is applied n times) is x if n is even and ~x if it is odd.
Thus, we can rewrite our general formula as ~nn2 ÷ 2 + 2 for all positive integers n.
Code
²~³¡H+2 Main link. Input: n
² Yield n².
~ Apply bitwise NOT to n²...
³¡ n times.
H Halve the result.
+2 Add 2.
JavaScript, 40 38 22 bytes
Using that new-fangled, fancy closed form solution that's all the rage!
n=>(n%2?3-n*n:4+n*n)/2
Thanks to ThomasKwa, I can eliminate my costly recursive function.
Jelly, 12 bytes
RṖµ²+‘×-*$SC
Try it here.