Sum of Squares


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

Introduction

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.

Understanding the Basics

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.

Main Concepts

To solve this problem, we need to:

Let's break down the steps with an example where n is 3:

  1. Initialize sum to 0.
  2. Iterate through numbers 1, 2, and 3.
  3. For each number, compute its square and add it to sum.

Examples and Use Cases

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 Pitfalls and Best Practices

Common mistakes include:

Best practices include:

Advanced Techniques

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.

Code Implementation

/**
 * 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

Debugging and Testing

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

Thinking and Problem-Solving Tips

When approaching this problem:

Conclusion

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.

Additional Resources