Given an integer n, we need to find the geometric sum of the following series using recursion.
1 + 1/3 + 1/9 + 1/27 + ... + 1/(3n)
Examples:
Input: n = 5
Output: 1.49794
Explanation: 1 + 1/3 + 1/9 + 1/27 + 1/81 + 1/243 = 1.49794
Input: n = 7
Output: 1.49977
Approach:
To find the geometric sum of the series 1 + 1/3 + 1/3² + ... + 1/3ⁿ. The base case returns 1 when n = 0. For each recursive call, the function adds 1/3ⁿ to the sum of the remaining terms. The recursion continues until n reaches 0, ensuring all terms are added.
// CPP implementation to Find the
// geometric sum of the series using recursion
#include <bits/stdc++.h>
using namespace std;
// function to find the sum of given series
double sum(int n)
{
// base case
if (n == 0)
return 1;
// calculate the sum each time
double ans = 1 / (double)pow(3, n) + sum(n - 1);
// return final answer
return ans;
}
// Driver code
int main()
{
// integer initialisation
int n = 5;
cout << sum(n) << endl;
return 0;
}
import java.util.*;
class GfG {
static double sum(int n)
{
// base case
if (n == 0)
return 1;
// calculate the sum each time
double ans = 1 / (double)Math.pow(3, n) + sum(n - 1);
// return final answer
return ans;
}
// Driver code
public static void main(String[] args)
{
// integer initialisation
int n = 5;
// print result
System.out.println(sum(n));
}
}
def sum(n):
# base case
if n == 0:
return 1
# calculate the sum each time
# and return final answer
return 1 / pow(3, n) + sum(n-1)
n = 5;
print(sum(n));
using System;
class GFG {
static double sum(int n)
{
// base case
if (n == 0)
return 1;
// calculate the sum each time
double ans = 1 / (double)Math.Pow(3, n) + sum(n - 1);
// return final answer
return ans;
}
// Driver code
static public void Main()
{
int n = 5;
Console.WriteLine(sum(n));
}
}
function sum(n)
{
// base case
if (n == 0)
return 1;
// calculate the sum each time
var ans = 1 / Math.pow(3, n) + sum(n - 1);
// return final answer
return ans;
}
// Driver code
// integer initialisation
var n = 5;
console.log(sum(n).toFixed(5));
Output
1.49794
Time Complexity: O(n)
Auxiliary Space: O(n), due to recursive function calls stored in the call stack.