Problem overview
The method SumOfSquares(int n) takes a non-negative integer n and returns 1² + 2² + ... + n². For n = 3 the sum is 1 + 4 + 9 = 14. For n = 0 there is nothing to add, so the result is 0.
Approach: accumulate one square per pass
The task has the shape of a running total: keep a variable sum, visit the numbers 1 to n in turn, and add the square of each to it. The loop counter supplies the numbers, and the body turns each one into its square and adds it. When the loop is done, sum holds the answer.
There is also a closed-form formula, n * (n + 1) * (2 * n + 1) / 6, but the lesson is about loops and accumulators, so it uses the direct approach. The loop version also makes each step visible, which is useful for debugging.
Step by step
- Declare
int sum = 0;. Zero is right because nothing has been added yet. - Write the loop header as
for (int i = 1; i <= n; i++). It starts at 1, since 0² adds nothing and the sum begins at 1². The condition is<=so thatnitself is included. - Add the square. Inside the loop, write
sum += i * i;. The operator+=adds the right side to the variable, so this meanssum = sum + i * i. Multiplication happens before the addition. - Return
sumafter the loop.
The solution in C#
class Solution {
public int SumOfSquares(int n) {
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i * i;
}
return sum;
}
}
Tracing n = 3, the value of sum after each pass is:
i = 1:sumis 0 + 1 = 1.i = 2:sumis 1 + 4 = 5.i = 3:sumis 5 + 9 = 14.
Then i becomes 4, the condition i <= n fails, and the method returns 14.
Some C# details:
- There is no power operator. C# has no
**or^for powers.^is the bitwise XOR operator, which gives unrelated results. Multiplyingi * iis the simplest way to square an integer.Math.Powexists, but it returns adoubleand would need a cast toint. - The loop variable is local.
iexists only inside the loop. The accumulatorsumis declared outside, so it survives after the loop and can be returned. - The class and method names are
SolutionandSumOfSquares. Code ported from other languages often hassumOfSquaresin lowercase, which does not match.
Complexity
Time: O(n). The loop runs n times, and each pass does a multiplication and an addition.
Space: O(1). The method keeps two integers, sum and i.
Edge cases and common mistakes
n = 0. The loop starts at 1, the condition1 <= 0is false at once, and the method returns 0.n = 1. The loop runs once and returns 1.- Integer overflow. An
intholds at most 2,147,483,647, and C# wraps silently when a result goes beyond that. The sum of squares passes the limit atn = 1861:SumOfSquares(1860)is 2146682110, butSumOfSquares(1861)would give a negative number. In the largest range you would declaresumas alongand writesum += (long)i * i. Note thati * iis computed inintfirst, so the cast has to be on one operand and not on the product. - Using
< n. That leaves outn². Forn = 3the result would be 5. - Starting at 0. This is harmless for the result (0² is 0), but it adds a useless pass.
- Adding
iinstead ofi * i. That computes the plain sum 1 + 2 + 3 = 6. - Squaring the total.
sum += ifollowed bysum * sumat the end computes the square of the sum, which is a different quantity (36 forn = 3).
Testing
n = 3gives14.n = 0gives0.n = 1gives1.n = 4gives30(1 + 4 + 9 + 16).n = 10gives385.