The GeeksforGeeks problem “Sum of first n terms” asks you to compute the value of
1³ + 2³ + 3³ + … + n³
and return the result. All calculations must be done recursively, no loops allowed.
Here’s the [Problem Link] to begin with.
Example
Inputn = 4
Series1³ + 2³ + 3³ + 4³ = 1 + 8 + 27 + 64
Output100
A well-known mathematical identity states that
1³ + 2³ + … + n³ = (n · (n + 1) / 2)²
…but when recursion is required, we’ll implement the summation directly via a functional approach.
Functional Recursion Solution
Intuition & Approach
- Base Case: The series stops at 1³ (
= 1
). - Recursive Case: For
num > 1
, return the current cubenum³
plus the result of the same function onnum − 1
. - This drives the recursion downward until it hits the base case, then the partial sums bubble back up the call stack.
Code Implementation
class Solution:
def func(self, num):
# Base case: the sum of the first 1 term is simply 1³ = 1
if num == 1:
return 1
# Recursive step: add the current cube and recurse on num - 1
return num**3 + self.func(num - 1)
def sumOfSeries(self, n):
# Entry point: delegate work to the recursive helper
return self.func(n)
Code Explanation
- Base Case (
num == 1
)- Returns
1
, ending further recursion.
- Returns
- Recursive Step
- Computes
num³
. - Calls
func(num − 1)
to sum the remaining cubes. - Adds them together and returns upward.
- Computes
- Driver (
sumOfSeries
) simply kicks off the helper with the originaln
.
Dry Run (n = 3)
Call Stack Level | num | Returned Value |
---|---|---|
1 | 3 | 27 + func(2) |
2 | 2 | 8 + func(1) |
3 (base) | 1 | 1 |
Unwinding:
func(1) → 1
func(2) → 8 + 1 = 9
func(3) → 27 + 9 = 36
Final answer: 36 (which matches (1 + 2 + 3)² = 6² = 36
).
Time & Space Complexity
- Time:
O(n)
– one function call per integer fromn
down to 1. - Space:
O(n)
– call-stack depth equalsn
because Python lacks tail-call optimization.
Conclusion
Using functional recursion gives an elegant, one-liner style recurrence:
Base Case + Self-Call = Solution.
While not as fast or space-efficient as the closed-form formula, it satisfies the “no loops” constraint and reinforces fundamental recursion concepts, perfect preparation for larger divide-and-conquer problems.
For any changes to the article, kindly email at code@codeanddebug.in or contact us at +91-9712928220.