JavaScript Code

How to find sum of squares of first n natural numbers using JavaScript?


Problem Statement

given a positive integer n, write a JavaScript program to find the sum of squares of first n natural numbers

Solution

to find the sum of squares of first n natural numbers using JavaScript, we can either use the formula n(n + 1)(2n + 1)/6, or iterate over a for loop from 1 to n and accumulate the sum of squares

Program

1. sum of squares of first n natural numbers using formula

n = 10;
sum = n * (n + 1) * (2 * n + 1) / 6;
console.log(`sum of squares of first ${n} natural numbers = ${sum}`);

in the above program, we have used arithmetic multiplication, arithmetic addition, arithmetic division

2. sum of first n natural numbers using for loop

n = 10;
sum = 0;
for ( let i = 1; i <= n; i++) {
    sum += i*i;
}
console.log(`sum of squares of first ${n} natural numbers = ${sum}`);