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/(3^n)
Examples:
Input N = 5
Output: 1.49794
Input: N = 7
Output: 1.49977
Approach:
In the above-mentioned problem, we are asked to use recursion. We will calculate the last term and call recursion on the remaining n-1 terms each time. The final sum returned is the result.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
double sum( int n)
{
if (n == 0)
return 1;
double ans = 1 / ( double ) pow (3, n) + sum(n - 1);
return ans;
}
int main()
{
int n = 5;
cout << sum(n) << endl;
return 0;
}
|
Java
import java.util.*;
class GFG {
static double sum( int n)
{
if (n == 0 )
return 1 ;
double ans = 1 / ( double )Math.pow( 3 , n) + sum(n - 1 );
return ans;
}
public static void main(String[] args)
{
int n = 5 ;
System.out.println(sum(n));
}
}
|
Python3
def sum (n):
if n = = 0 :
return 1
return 1 / pow ( 3 , n) + sum (n - 1 )
n = 5 ;
print ( sum (n));
|
C#
using System;
class GFG {
static double sum( int n)
{
if (n == 0)
return 1;
double ans = 1 / ( double )Math.Pow(3, n) + sum(n - 1);
return ans;
}
static public void Main()
{
int n = 5;
Console.WriteLine(sum(n));
}
}
|
Javascript
<script>
function sum(n)
{
if (n == 0)
return 1;
var ans = 1 / Math.pow(3, n) + sum(n - 1);
return ans;
}
var n = 5;
document.write( sum(n).toFixed(5));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
09 Aug, 2021
Like Article
Save Article