887939. Sum of Squares of First n Natural Numbers
Easy
Sum of Squares of First n Natural Numbers
Summary
Given a positive integer n, find the sum of squares of the first n natural numbers. This problem is a classic example of a mathematical algorithm, where we need to calculate the sum of squares of integers from 1 to n.
Detailed Explanation
The key concept involved in this problem is the formula for the sum of squares of the first n natural numbers. The formula is given by:
1^2 + 2^2 + ... + n^2 = Σ(i^2) from i=1 to n
To calculate the sum, we can use a simple loop that iterates from 1 to n, and at each iteration, we add the square of the current number to our running total.
Here's a step-by-step breakdown of the solution:
- Initialize a variable
sumto 0. - Iterate from 1 to
n. - At each iteration, calculate the square of the current number (
i) and add it tosum. - Return
sumas the result.
Time complexity: O(n) Space complexity: O(1)
Optimized Solutions
Java
public int sumOfSquares(int n) {
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i * i;
}
return sum;
}