Last active
August 10, 2020 21:40
-
-
Save noel-yap/fe5bc98bee6d43dd32f0f129cbc2f79f to your computer and use it in GitHub Desktop.
Number spiral diagonals: https://projecteuler.net/problem=28
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class Solution { | |
| // The sum of each square is: | |
| // `1`; n == 1 | |
| // `4n² + n²-(n-1) + n²-2(n-1) + n²-3(n-1)`; n > 1 | |
| // or `4n² - 6(n-1)` | |
| // | |
| // Substituting `n = 2k+1`: | |
| // `Σ(k ≤ K)(4(2k+1)² - 6(2k+1-1))` | |
| // `Σ(k ≤ K)(4(4k²+4k+1) - 12k)` | |
| // `4Σ(k ≤ K)(4k²+4k+1 - 3k)` | |
| // `4Σ(k ≤ K)(4k² + k + 1)` | |
| // | |
| // The total sum of the diagonals is therefore: | |
| // `1 + 4Σ(1 ≤ k ≤ K)(4k² + k + 1)`; K = ½(N-1) and the first term is for N == 1 | |
| // | |
| // Substituting the closed form for the sum of sequence of squares, etc: | |
| // `1 + 4(⅔K(K+1)(2K+1) + ½K(K+1) + K)` | |
| // `1 + 4(⅙K(K+1)(8K+7) + K))` | |
| // | |
| // Substituting back and simplifying: | |
| // `1 + 4(⅙(½(N-1)(½(N-1)+1)(4(N-1)+7) + ½(N-1))` | |
| // `1 + 4(½(N-1)½(N+1)⅙(4N+3) + ½(N-1))` | |
| // `1 + 4(¼(N²-1)⅙(4N+3) + ½(N-1))` | |
| // `1 + ⅙(N²-1)(4N+3) + 2(N-1)` | |
| // `⅙(N²-1)(4N+3) + 2N - 1` | |
| public long sumOfDiagonals(long n) { | |
| return (n * n - 1) * (4 * n + 3) / 6 + 2 * n - 1; | |
| } | |
| @Test | |
| public void eyeballTest() { | |
| for (long n = 1; n < 1003; n += 2) { | |
| System.out.println("n = " + n + "; sOD(n) = " + sumOfDiagonals(n)); | |
| } | |
| } | |
| public static void main(String[] args) { | |
| JUnitCore.main("Solution"); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment