Given a non-negative integer n, compute and return the sum of
12 + 22 + 32 + ... + n2
Example:
Input: n = 3 Output: 14 Explanation: 12 + 22 + 32 = 1 + 4 + 9 = 14
In this lesson, we will explore how to compute the sum of squares of the first n
natural numbers. This is a common problem in programming that helps in understanding loops and basic arithmetic operations. The sum of squares has applications in various fields such as statistics, physics, and computer science.
The fundamental concept here is to compute the sum of squares of numbers from 1 to n
. For example, if n
is 3, we need to calculate 12 + 22 + 32. This requires iterating through each number from 1 to n
and summing their squares.
To solve this problem, we need to:
n
.Let's break down the steps with an example where n
is 3:
sum
to 0.sum
.Consider the following example:
Input: n = 4 Output: 30 Explanation: 12 + 22 + 32 + 42 = 1 + 4 + 9 + 16 = 30
This approach can be used in scenarios where you need to calculate the sum of squares for statistical analysis or in algorithms that require such computations.
Common mistakes include:
Best practices include:
n
.For large values of n
, the iterative approach might be inefficient. An advanced technique involves using the formula for the sum of squares:
Sum = n(n + 1)(2n + 1) / 6
This formula provides a direct computation without the need for a loop.
/**
* Function to compute the sum of squares of the first n natural numbers
* @param {number} n - A non-negative integer
* @returns {number} - The sum of squares from 1 to n
*/
function sumOfSquares(n) {
// Initialize sum to 0
let sum = 0;
// Iterate from 1 to n
for (let i = 1; i <= n; i++) {
// Add the square of i to sum
sum += i * i;
}
// Return the computed sum
return sum;
}
// Example usage:
console.log(sumOfSquares(3)); // Output: 14
To debug, ensure that the loop runs correctly and the sum is updated as expected. Use console logs to print intermediate values. For testing, consider edge cases such as n = 0
and n = 1
.
// Test cases
console.log(sumOfSquares(0)); // Output: 0
console.log(sumOfSquares(1)); // Output: 1
console.log(sumOfSquares(5)); // Output: 55
When approaching this problem:
n
to verify correctness.We have covered how to compute the sum of squares of the first n
natural numbers using a loop. Understanding this concept is crucial for solving more complex problems in programming. Practice with different values of n
to master this technique.