YouTip LogoYouTip

Python Cube Sum

## Python Program to Find the Sum of Cubes of First n Natural Numbers In this tutorial, you will learn how to calculate the sum of the cubes of the first $n$ natural numbers using Python. This is a classic mathematical problem often used to practice loops, recursion, and mathematical optimizations in programming. --- ### Mathematical Formula The sum of the cubes of the first $n$ natural numbers is represented as: $$S = 1^3 + 2^3 + 3^3 + 4^3 + \dots + n^3$$ #### Examples: * **Input:** $n = 5$ **Calculation:** $1^3 + 2^3 + 3^3 + 4^3 + 5^3 = 1 + 8 + 27 + 64 + 125 = 225$ **Output:** `225` * **Input:** $n = 7$ **Calculation:** $1^3 + 2^3 + 3^3 + 4^3 + 5^3 + 6^3 + 7^3 = 784$ **Output:** `784` --- ### Method 1: Using an Iterative Loop (Basic Approach) The most straightforward way to solve this is by iterating from $1$ to $n$ using a `for` loop and accumulating the cube of each number. #### Python Code ```python def sum_of_cubes(n): total_sum = 0 # Iterate from 1 to n (inclusive) for i in range(1, n + 1): total_sum += i * i * i # Or use the exponentiation operator: i ** 3 return total_sum # Test the function n = 5 result = sum_of_cubes(n) print(f"The sum of cubes of the first {n} natural numbers is: {result}") ``` #### Output ```text The sum of cubes of the first 5 natural numbers is: 225 ``` --- ### Method 2: Using the Mathematical Formula (O(1) Time Complexity) For larger values of $n$, running a loop can be slow. We can optimize this to run in $O(1)$ constant time using the standard mathematical formula for the sum of cubes: $$S = \left( \frac{n \times (n + 1)}{2} \right)^2$$ This formula is derived from the fact that the sum of cubes of the first $n$ natural numbers is equal to the square of the sum of the first $n$ natural numbers. #### Python Code ```python def sum_of_cubes_formula(n): # Apply the mathematical formula: [n * (n + 1) / 2] ^ 2 # We use integer division (//) to ensure the result remains an integer total_sum = (n * (n + 1) // 2) ** 2 return total_sum # Test the function n = 7 result = sum_of_cubes_formula(n) print(f"The sum of cubes of the first {n} natural numbers is: {result}") ``` #### Output ```text The sum of cubes of the first 7 natural numbers is: 784 ``` --- ### Method 3: Using Python's Built-in Functions (Pythonic Approach) You can write a highly concise, single-line solution using Python's built-in `sum()` function combined with a generator expression. #### Python Code ```python def sum_of_cubes_pythonic(n): # Generate cubes on the fly and sum them up return sum(i**3 for i in range(1, n + 1)) # Test the function n = 5 print(f"The sum of cubes of the first {n} natural numbers is: {sum_of_cubes_pythonic(n)}") ``` #### Output ```text The sum of cubes of the first 5 natural numbers is: 225 ``` --- ### Comparison of Methods | Method | Time Complexity | Space Complexity | Best Used For | | :--- | :--- | :--- | :--- | | **Iterative Loop** | $O(n)$ | $O(1)$ | Beginners learning basic control flow and loops. | | **Mathematical Formula** | $O(1)$ | $O(1)$ | Production environments and large values of $n$ (highly optimized). | | **Pythonic (Generator)** | $O(n)$ | $O(1)$ | Writing clean, readable, and concise Python code. | ### Considerations 1. **Integer Overflow:** Unlike many other programming languages (like C++ or Java), Python automatically handles arbitrarily large integers. You do not need to worry about integer overflow when calculating the sum of cubes for very large values of $n$. 2. **Division Operator:** In the mathematical formula method, using the standard division operator `/` converts the result into a float (e.g., `225.0`). Using the floor division operator `//` ensures the output remains a clean integer (`225`).
← Python3 Array RotationJava Quiz β†’