Skip to content

Instantly share code, notes, and snippets.

@dfkaye
Created December 27, 2022 04:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dfkaye/b699fc9e79f3c9d73d4347b06aad3dff to your computer and use it in GitHub Desktop.
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}
// 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