JavaScript Code


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


Find sum of squares of first n natural numbers in JavaScript

In this tutorial, you are given a positive integer n, and you to 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.

Programs

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}`);