Open In App

Sum of Squares of First N Natural Numbers in JavaScript

Last Updated : 12 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The sum of squares of the first n natural numbers is a mathematical problem of finding the sum of squares of each number up to a given positive number n. We can find the sum of squares of first n natural numbers in JavaScript using the approaches listed below.

Sum of Square of First N Natural Numbers using for Loop

The for loop is used to calculate the sum of the squares of first N natural numbers. First, initialize a variable sum with 0 then iterating over the numbers from 1 to N and adding the square of each number to the sum variable.

Syntax:

for (initialization; condition; update) {
    // Code
}

Example: This example uses the for loop to get a sum of squares of first n natural numbers in JavaScript.

Javascript
let n = 8;
let sum = 0;
for (let i = 1; i <= n; i++) {
    sum += i * i;
}
console.log(sum); 

Output
204

Sum of Square of First N Natural Numbers using reduce() Method

Creates an array of numbers from 1 to n, then use the reduce() method to accumulate the sum of squares, by starting with an initial value of 0.

Syntax:

array.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue]) 

Example: This example uses the reduce() method to get a sum of squares of first n natural numbers in JavaScript.

Javascript
let n = 8;
let numbers = Array.from({ length: n }, (_, i) => i + 1);
let sum = numbers.reduce((acc, num) => acc + num * num, 0);
console.log(sum); 

Output
204

Sum of Square of First N Natural Numbers using Mathematical Formula

This approach uses the direct mathematical formula (n * (n + 1) * (2 * n + 1)) / 6 to calculate the sum of the squares of the first n natural numbers.

Syntax:

Sum = (n * (n + 1) * (2 * n + 1)) / 6;

Example: This example uses the mathematical formula to get a sum of squares of first n natural numbers in JavaScript.

Javascript
let n = 8;
let sum = (n * (n + 1) * (2 * n + 1)) / 6;
console.log(sum);

Output
204

Sum of Square of First N Natural Numbers using Recursion:

This approach uses a recursive function to find the sum of squares. The base case has the current number greater than n, in which case it returns 0; otherwise, it gets the square of the current number and adds this to the result of next number’s recursive call.

Syntax

const sum = (n, current = 1) => (current > n) ? 0 : current * current + sum(n, current + 1);

Example: This example uses recursion to get a sum of squares of first n natural numbers in JavaScript

Javascript
function sumOfSquaresRecursion(n, current = 1) {
    if (current > n) {
        return 0;
    }
    return (
        current * current +
        sumOfSquaresRecursion(n, current + 1)
    );
}

// Example usage:
let n = 8;
console.log(sumOfSquaresRecursion(n));

Output
204




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads