Skip to content

Commit 03d3720

Browse files
committed
add a solution for Project Euler problem #6
1 parent 74d5715 commit 03d3720

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

Project-Euler/Problem006.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/*
2+
Sum square difference
3+
The sum of the squares of the first ten natural numbers is 385,
4+
5+
The square of the sum of the first ten natural numbers is 3025,
6+
7+
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 - 385 = 2640.
8+
9+
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
10+
*/
11+
12+
const findSumSquareDifference = (elementsCount) => {
13+
const naturalNumbers = Array(elementsCount).fill().map((_, i) => i + 1)
14+
15+
let sumOfSquares = 0
16+
naturalNumbers.forEach(number => { sumOfSquares += Math.pow(number, 2) })
17+
18+
const sumOfNumbers = naturalNumbers.reduce((prev, current) => { current += prev }, 0)
19+
const squareOfSums = Math.pow(sumOfNumbers, 2)
20+
21+
return squareOfSums - sumOfSquares
22+
}
23+
24+
console.log(findSumSquareDifference(20))

0 commit comments

Comments
 (0)