Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program for cube sum of first n natural numbers
In this article, we will learn how to calculate the cube sum of first n natural numbers using two different approaches. The cube sum series is: 1³ + 2³ + 3³ + 4³ + ... + n³.
Problem statement ? Given an input n, we need to print the sum of series 1³ + 2³ + 3³ + 4³ + ... + n³ till n-th term.
Here we will discuss two approaches to solve this problem ?
- Brute-force approach using loops
- Mathematical solution using the sum formula
Using Loop (Iterative Approach)
This approach computes the cube of each number and adds it to the running sum ?
def sumOfSeries(n):
sum_cubes = 0
for i in range(1, n + 1):
sum_cubes += i * i * i
return sum_cubes
# Driver code
n = 3
print("Sum of cubes of first", n, "natural numbers:", sumOfSeries(n))
The output of the above code is ?
Sum of cubes of first 3 natural numbers: 36
Using Mathematical Formula
We can use the mathematical formula for cube sum: Sum = (n × (n + 1) / 2)²
This formula is derived from the fact that the sum of cubes equals the square of the sum of natural numbers ?
def sumOfSeries(n):
x = (n * (n + 1) // 2)
return x * x
# Driver code
n = 3
print("Sum of cubes of first", n, "natural numbers:", sumOfSeries(n))
The output of the above code is ?
Sum of cubes of first 3 natural numbers: 36
Comparison of Both Approaches
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Loop | O(n) | O(1) | Understanding the concept |
| Formula | O(1) | O(1) | Large values of n |
Example with Larger Value
def sumOfSeries_loop(n):
sum_cubes = 0
for i in range(1, n + 1):
sum_cubes += i * i * i
return sum_cubes
def sumOfSeries_formula(n):
x = (n * (n + 1) // 2)
return x * x
# Test with n = 5
n = 5
print("Using loop:", sumOfSeries_loop(n))
print("Using formula:", sumOfSeries_formula(n))
print("Verification: 1³ + 2³ + 3³ + 4³ + 5³ =", 1**3 + 2**3 + 3**3 + 4**3 + 5**3)
The output of the above code is ?
Using loop: 225 Using formula: 225 Verification: 1³ + 2³ + 3³ + 4³ + 5³ = 225
Conclusion
Both approaches solve the cube sum problem effectively. The iterative method helps understand the concept, while the mathematical formula provides O(1) time complexity for better performance with large values.
