Created
December 27, 2022 04:57
-
-
Save dfkaye/b699fc9e79f3c9d73d4347b06aad3dff to your computer and use it in GitHub Desktop.
math diversion: find difference between square of the sum of numbers {1 ,n} and the sum of the squares {1, n}
This file contains 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
// 26 Dec 2022 | |
// A diversion. | |
// Find the difference between the square of the sum of the numbers | |
// from 1 to n, and the sum of the squares from 1 to n. | |
function squareOfSum(n) { | |
if (+n !== +n) { | |
return 0 | |
} | |
// square pyramidal numbers | |
var sum = n * (n + 1) / 2 | |
return sum * sum; | |
} | |
console.group("squareOfSum") | |
console.log( | |
squareOfSum(1), | |
squareOfSum(2), | |
squareOfSum(3) | |
) | |
console.groupEnd("squareOfSum") | |
function sumOfSquares(n) { | |
if (+n !== +n) { | |
return 0 | |
} | |
// triangular numbers | |
var i = 2 | |
var j = 3 | |
var k = (n * n * n) * i | |
var s = (n * n) * j | |
return (k + s + n) / (2 * 3) | |
} | |
console.group("sumOfSquares") | |
console.log( | |
sumOfSquares(1), | |
sumOfSquares(2), | |
sumOfSquares(3) | |
) | |
console.groupEnd("sumOfSquares") | |
function diffSquares(n) { | |
if (+n !== +n) { | |
return 0 | |
} | |
return squareOfSum(n) - sumOfSquares(n) | |
} | |
console.group("diffSquares") | |
console.log( | |
diffSquares(1), | |
diffSquares(2), | |
diffSquares(3) | |
) | |
console.groupEnd("diffSquares") | |
/* | |
squareOfSum | |
1 9 36 | |
sumOfSquares | |
1 5 14 | |
diffSquares | |
0 4 22 | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment