Start learning free

LESSON 139 OF 410 · LOOPS & GLOBAL VARIABLES

Sum of Squares

Practice Read the full explanation

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
Hints:

Where should we store this sum as we compute it?

We can use a variable sum, initially equal to 0. We have to iterate through the numbers 1 to n. How can we do this?

Let's use a for loop and a variable i to iterate through the numbers 1 to n. What should we do inside this loop?

Inside the loop, all we should do is add i * i to sum.
When the loop terminates, the answer lies in sum.

STEP 1 OF 4
    Ctrl + Enter to check

    JAVASCRIPT · LOOPS & GLOBAL VARIABLES

    Sum Of Squares in JavaScript, explained

    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:

    • Initialize a variable to store the sum.
    • Use a loop to iterate through numbers from 1 to n.
    • Square each number and add it to the sum.

    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:

    • Not initializing the sum variable.
    • Incorrect loop boundaries.
    • Forgetting to square the number before adding it to the sum.

    Best practices include:

    • Using meaningful variable names.
    • Ensuring the loop runs from 1 to n.
    • Adding comments to explain each step of the code.

    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:

    • Break it down into smaller steps.
    • Write pseudocode before actual implementation.
    • Test with small values of n to verify correctness.

    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

    Keep going with JavaScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free