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 = 14Hints:
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.
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check