|
| 1 | +/** |
| 2 | + * Problem 28 - Number spiral diagonals |
| 3 | + * |
| 4 | + * @see {@link https://projecteuler.net/problem=28} |
| 5 | + * |
| 6 | + * Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows: |
| 7 | + * |
| 8 | + * 21 22 23 24 25 |
| 9 | + * 20 07 08 09 10 |
| 10 | + * 19 06 01 02 11 |
| 11 | + * 18 05 04 03 12 |
| 12 | + * 17 16 15 14 13 |
| 13 | + * |
| 14 | + * It can be verified that the sum of the numbers on the diagonals is 101. |
| 15 | + * What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way? |
| 16 | + * |
| 17 | + * @author ddaniel27 |
| 18 | + */ |
| 19 | + |
| 20 | +function problem28 (dim) { |
| 21 | + if (dim % 2 === 0) { |
| 22 | + throw new Error('Dimension must be odd') |
| 23 | + } |
| 24 | + if (dim < 1) { |
| 25 | + throw new Error('Dimension must be positive') |
| 26 | + } |
| 27 | + |
| 28 | + let result = 1 |
| 29 | + for (let i = 3; i <= dim; i += 2) { |
| 30 | + /** |
| 31 | + * Adding more dimensions to the matrix, we will find at the top-right corner the follow sequence: |
| 32 | + * 01, 09, 25, 49, 81, 121, 169, ... |
| 33 | + * So this can be expressed as: |
| 34 | + * i^2, where i is all odd numbers |
| 35 | + * |
| 36 | + * Also, we can know which numbers are in each corner dimension |
| 37 | + * Just develop the sequence counter clockwise from top-right corner like this: |
| 38 | + * First corner: i^2 |
| 39 | + * Second corner: i^2 - (i - 1) | The "i - 1" is the distance between corners in each dimension |
| 40 | + * Third corner: i^2 - 2 * (i - 1) |
| 41 | + * Fourth corner: i^2 - 3 * (i - 1) |
| 42 | + * |
| 43 | + * Doing the sum of each corner and simplifing, we found that the result for each dimension is: |
| 44 | + * sumDim = 4 * i^2 + 6 * (1 - i) |
| 45 | + * |
| 46 | + * In this case I skip the 1x1 dim matrix because is trivial, that's why I start in a 3x3 matrix |
| 47 | + */ |
| 48 | + result += (4 * i * i) + 6 * (1 - i) // Calculate sum of each dimension corner |
| 49 | + } |
| 50 | + return result |
| 51 | +} |
| 52 | + |
| 53 | +export { problem28 } |
0 commit comments