Start learning free

LESSON 138 OF 409 · LOOPS & GLOBAL VARIABLES

Sum of Squares in C++ (Time Complexity: O(n))

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

    C++ · LOOPS & GLOBAL VARIABLES

    Sum Of Squares in C++, explained

    Understanding the Problem

    The core challenge of this problem is to compute the sum of squares of the first n natural numbers efficiently. This problem is significant in various mathematical and computational applications, such as statistical calculations and algorithm analysis. A common pitfall is to overlook the efficiency of the solution, especially for large values of n.

    Approach

    To solve this problem, we can start with a naive approach and then discuss an optimized solution.

    Naive Approach

    The naive approach involves iterating through each number from 1 to n and summing their squares. This approach is straightforward but not the most efficient for very large values of n.

    Optimized Approach

    An optimized approach leverages the mathematical formula for the sum of squares of the first n natural numbers:

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

    This formula allows us to compute the sum in constant time, O(1), which is significantly faster than the naive approach.

    Algorithm

    Naive Approach

    1. Initialize a variable sum to 0.
    2. Iterate through each number i from 1 to n.
    3. For each i, add i * i to sum.
    4. Return the value of sum.

    Optimized Approach

    1. Use the formula Sum = n(n + 1)(2n + 1) / 6 to compute the sum directly.
    2. Return the computed value.

    Code Implementation

    Naive Approach

    
    #include <iostream>
    
    int sumOfSquaresNaive(int n) {
        int sum = 0;
        for (int i = 1; i <= n; ++i) {
            sum += i * i; // Add the square of i to sum
        }
        return sum;
    }
    
    int main() {
        int n = 3;
        std::cout << "Sum of squares (Naive): " << sumOfSquaresNaive(n) << std::endl;
        return 0;
    }
    

    Optimized Approach

    
    #include <iostream>
    
    int sumOfSquaresOptimized(int n) {
        return (n * (n + 1) * (2 * n + 1)) / 6; // Use the formula to compute the sum
    }
    
    int main() {
        int n = 3;
        std::cout << "Sum of squares (Optimized): " << sumOfSquaresOptimized(n) << std::endl;
        return 0;
    }
    

    Complexity Analysis

    Naive Approach: The time complexity is O(n) because we iterate through each number from 1 to n. The space complexity is O(1) as we use a constant amount of extra space.

    Optimized Approach: The time complexity is O(1) because we compute the sum using a constant-time formula. The space complexity is also O(1).

    Edge Cases

    Consider the following edge cases:

    • n = 0: The sum should be 0.
    • n = 1: The sum should be 1 (12).
    • Large values of n: Ensure the solution handles large values efficiently.

    Testing

    To test the solution comprehensively, consider the following test cases:

    • Simple cases: n = 0, n = 1, n = 2, n = 3
    • Edge cases: n = 0, n = 1
    • Large cases: n = 1000, n = 10000

    Thinking and Problem-Solving Tips

    When approaching such problems, consider both the brute-force and optimized solutions. Understanding the underlying mathematical principles can often lead to more efficient algorithms. Practice by solving similar problems and studying different algorithms to improve problem-solving skills.

    Conclusion

    In this blog post, we discussed how to compute the sum of squares of the first n natural numbers using both naive and optimized approaches. We analyzed the complexity of each approach and provided well-commented C++ code implementations. Understanding and solving such problems is crucial for developing efficient algorithms and improving problem-solving skills.

    Additional Resources

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