Skip to content

Commit 829d3fd

Browse files
authored
solution: Project Euler Problem 28 (TheAlgorithms#1198)
1 parent 2a62eab commit 829d3fd

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed

Project-Euler/Problem028.js

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
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 }

Project-Euler/test/Problem028.test.js

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import { problem28 } from '../Problem028.js'
2+
3+
describe('checking number spiral diagonals', () => {
4+
it('should be invalid input if number is negative', () => {
5+
expect(() => problem28(-3)).toThrowError('Dimension must be positive')
6+
})
7+
it('should be invalid input if number is not odd', () => {
8+
expect(() => problem28(4)).toThrowError('Dimension must be odd')
9+
})
10+
test('if the number is equal to 5 result should be 101', () => {
11+
expect(problem28(5)).toBe(101)
12+
})
13+
// Project Euler Condition Check
14+
test('if the number is equal to 1001 result should be 669171001', () => {
15+
expect(problem28(1001)).toBe(669171001)
16+
})
17+
})

0 commit comments

Comments
 (0)