The sum of the first n squares has a closed form that can be proved by induction. Your program computes the sum both ways for k = 1 to n, so you can see the two agree before you trust the formula.
What to build
A program that prints the running sum of squares next to the formula's value.
Requirements
- Read n.
- For each k from 1 to n print
k total formula, where total is 1² + 2² + ... + k² added up one by one, and formula is k(k + 1)(2k + 1)/6.
Input
One whole number n.
Output
n lines with three numbers each.
Constraints
1 ≤ n ≤ 30.
Example
Input:
3
Output:
1 1 1
2 5 5
3 14 14
Why it works
The running total is the left side of the claim and the closed form is the right side. Agreement for k = 1 is the base case, and agreement for every next k, because the total grows by (k + 1) squared and the formula grows by the same amount, is what the inductive step proves.
Examples
3
1 1 1 2 5 5 3 14 14
1
1 1 1
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Keep a running total: add k * k each time round the loop.
Hint 2
The formula for the sum of the first k squares is k * (k + 1) * (2 * k + 1) // 6.
Hint 3
Print k, the running total and the formula's value on one line.
Solution
Show one correct solution (try it yourself first)
n = int(input())
total = 0
for k in range(1, n + 1):
total += k * k
print(k, total, k * (k + 1) * (2 * k + 1) // 6)
▶ Open this solution in the compiler, then press Visualize to watch it run step by step