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
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
Sum of Squares of First N Natural Numbers in JavaScript
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.
Table of Content
- Sum of Square of First N Natural Numbers using for Loop
- Sum of Square of First N Natural Numbers using reduce() Method
- Sum of Square of First N Natural Numbers using Mathematical Formula
- Sum of Square of First N Natural Numbers using Recursion