Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Sum of Cubes

Add cubes from one through n with a running total. Students trace term construction and distinguish summing cubed values from cubing the final ordinary sum.

IntermediatePhase 6 - Category 4: Mathematical CombinationsExample 2 of 10
sum-of-cubes.py
1# Take n
2n = int(input("Enter n: "))
3
4# Calculate sum of cubes
5total = 0
6for i in range(1, n + 1):
7 total += i * i * i
8
9print(f"Sum of cubes: {total}")

Output

Enter n: 5
Sum of cubes: 225

In this one

  • Calculate cubes per term
  • Accumulate integer products
  • Avoid XOR confusion

How it works

  1. 1

    Start with total zero.

  2. 2

    Add i * i * i for each positive term through n.

  3. 3

    Print the sum after the loop.

Edge cases

What if n is negative?

What if n is negative?

No terms are visited, so the result stays zero.

Is ^ a power operator?

Is ^ a power operator?

No. Python uses ** for powers.

What's going on

Each iteration adds i * i * i to total. The three factors calculate a cube using ordinary multiplication.

For n equal to three, the result is 1 + 8 + 27 = 36. The final print occurs after the full traversal. An empty range leaves zero. ** 3 could also express a cube, while ^ 3 would be bitwise XOR and would not match this lesson.

What if n is negative? No terms are visited, so the result stays zero.

Is ^ a power operator? No. Python uses ** for powers.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What is added for i = 2?

Pick an answer to check it.

Question 2

What if n is negative?

Pick an answer to check it.

Questions people ask

What if n is negative?

No terms are visited, so the result stays zero.

Is ^ a power operator?

No. Python uses ** for powers.

What is added for i = 2?

8.