- You are not initialising
sum
. Initialise it with 0
.
- You shouldn't be adding
n
at each step, but j
.
Of course, this is to fix your current code. There are better approaches to solving the problem, which others have already mentioned.
Edit:
Just for fun, here's a formula that allows you to solve the problem in O(1)
:
Your sum is equal to n*(n + 1)*(2*n + 1) / 12 + n*(n + 1) / 4
.
This is obtained by writing it as a sum and using the fact that the sum of the first n
consecutive squares is n(n + 1)(2n + 1) / 6
and the sum of the first n
positive ints is n(n + 1)/2
. +1 if you can find a nicer form of the formula.