Problem 7. squaresum.js

 /*Square Sum

Given a natural number n as input, find the sum of squares of first n natural numbers.

Input
One Integer, denoting n.

Output
One Integer, denoting the required sum.

Example
Input: 3

Output: 14

Explanation:

1*1+2*2+3*3 = 14
*/

let fs = require("fs");
let data = fs.readFileSync(0, 'utf-8');
let idx = 0;
data = data.split('\n');

function readLine() {
idx++;
return data[idx - 1].trim();
}
//.......................................................................................

// sum of square of first n natural numbers formula:

// [n(n+1)(2n+1)] / 6

let n = parseInt(readLine()); // 3

let sumOfSquares = [n * (n + 1) * [(2 * n) + 1]] / 6; // this is the formula

console.log(sumOfSquares); //14

Terminal:
Nobins-MacBook-Pro:STOC_MODULE 11SEPT 2022 nobinpunyo$ node squaresum.js <input.txt 14


Comments

Popular posts from this blog

Problem 33. patter122333.js

Problem 38. diamond.js

Problem 16. chocolatebills.js