2018-10-12 15:37:13 -04:00
|
|
|
---
|
|
|
|
title: Sum square difference
|
|
|
|
---
|
2019-07-24 00:59:27 -07:00
|
|
|
# Problem 6: Sum square difference
|
2018-10-12 15:37:13 -04:00
|
|
|
|
2019-07-24 00:59:27 -07:00
|
|
|
---
|
|
|
|
## Problem Explanation
|
2018-10-12 15:37:13 -04:00
|
|
|
- Sum of first n natural numbers can be calculated by using this formula:
|
|
|
|
- 
|
|
|
|
|
|
|
|
- Sum of squares of n natural numbers can be calculated by using this formula:
|
|
|
|
- 
|
|
|
|
|
|
|
|
- We can calculate the values using the above formula and subtract them to get the result.
|
|
|
|
|
2019-07-24 00:59:27 -07:00
|
|
|
|
|
|
|
---
|
|
|
|
## Solutions
|
|
|
|
<details><summary>Solution 1 (Click to Show/Hide)</summary>
|
|
|
|
|
2018-10-12 15:37:13 -04:00
|
|
|
```js
|
|
|
|
function sumSquareDifference(n) {
|
|
|
|
const sumOfN = (n*(n+1))/2;
|
|
|
|
const sumOfNSquare = (n*(n+1)*(2*n+1))/6;
|
|
|
|
|
|
|
|
//** is exponentaial operator added in ES7, it's equivalent to Math.pow(num, 2)`
|
|
|
|
return (sumOfN ** 2) - sumOfNSquare;
|
|
|
|
}
|
|
|
|
```
|
2019-07-01 06:49:24 -07:00
|
|
|
|
2019-07-24 00:59:27 -07:00
|
|
|
#### Relevant Links
|
2018-10-12 15:37:13 -04:00
|
|
|
|
|
|
|
- [Sum of n numbers - Wikipedia](https://en.wikipedia.org/wiki/1_%2B_2_%2B_3_%2B_4_%2B_%E2%8B%AF)
|
|
|
|
- [Sum of n square numbers - Wikipedia](https://en.wikipedia.org/wiki/Square_pyramidal_number)
|
2019-07-24 00:59:27 -07:00
|
|
|
|
|
|
|
</details>
|