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
The core challenge of this problem is to compute the sum of squares of the first n
natural numbers. This problem is significant in various mathematical and computational applications, such as in statistical formulas and algorithm analysis.
Potential pitfalls include misunderstanding the range of numbers to sum (from 1 to n
) and ensuring the correct calculation of squares.
To solve this problem, we can use a simple iterative approach:
sum
to 0.n
.i
, add i * i
to sum
.sum
.This approach is straightforward and easy to understand. However, it is not the most optimized in terms of mathematical elegance.
Here is a step-by-step breakdown of the algorithm:
sum
to 0.for
loop to iterate from 1 to n
.sum
.sum
.def sum_of_squares(n):
# Initialize the sum to 0
total_sum = 0
# Iterate from 1 to n
for i in range(1, n + 1):
# Add the square of i to the total sum
total_sum += i * i
# Return the computed sum
return total_sum
# Example usage
n = 3
print(sum_of_squares(n)) # Output: 14
The time complexity of this approach is O(n)
because we iterate through the numbers from 1 to n
once. The space complexity is O(1)
as we only use a constant amount of extra space for the sum
variable.
Potential edge cases include:
n = 0
: The sum should be 0.n
: Ensure the algorithm handles large inputs efficiently.Examples:
sum_of_squares(0) # Output: 0
sum_of_squares(1) # Output: 1
sum_of_squares(1000) # Output: 333833500
To test the solution comprehensively, consider a variety of test cases:
n = 1, 2, 3
n = 0
n = 1000, 10000
Example test cases:
assert sum_of_squares(0) == 0
assert sum_of_squares(1) == 1
assert sum_of_squares(2) == 5
assert sum_of_squares(3) == 14
assert sum_of_squares(10) == 385
assert sum_of_squares(1000) == 333833500
When approaching such problems:
Understanding and solving the sum of squares problem helps in grasping basic iteration and summation concepts. It is a fundamental problem that appears in various mathematical and computational contexts. Practice and exploration of similar problems can further enhance problem-solving abilities.
For further reading and practice: