Computer >> Computer tutorials >  >> Programming >> Javascript

Difference between sum of square and square of sum in JavaScript


We are required to write a JavaScript function that takes a number, say n, as the one and the only input.

The function should −

  • Calculate the sum of squares of the first n natural numbers.

  • Calculate the square of sums of first n natural numbers.

  • Return the absolute difference between the both figures obtained.

For example: If n = 5;

Then,

sum of squares = 1 + 4 + 9 + 16 + 25 = 55
square of sums = 15 * 15 = 225

Hence, output = 225 − 55 = 170

Example

The code for this will be −

const squareDifference = (num = 1) => {
   let x = 0;
   let y = 0;
   let i = 0;
   let j = 0;
   // function to compute the sum of squares
   (function sumOfSquares() {
      while (i <= num) {
         x += Math.pow(i, 2);
         i++;
      }
      return x;
   }());
   // function to compute the square of sums
   (function squareOfSums() {
      while (j <= num) {
         y += j;
         j++;
      }
      y = Math.pow(y, 2);
      return y;
   }());
   // returning the absolute difference
   return Math.abs(y − x);
};
console.log(squareDifference(1));
console.log(squareDifference(5));
console.log(squareDifference(10));
console.log(squareDifference(15));

Output

And the output in the console will be −

0
170
2640
13160