Sum of an Infinite Geometric Progression ( GP )
Last Updated :
20 Jul, 2022
Given two integers A and R, representing the first term and the common ratio of a geometric sequence, the task is to find the sum of the infinite geometric series formed by the given first term and the common ratio.
Examples:
Input: A = 1, R = 0.5
Output: 2
Input: A = 1, R = -0.25
Output: 0.8
Approach: The given problem can be solved based on the following observations:
- If absolute of value of R is greater than equal to 1, then the sum will be infinite.
- Otherwise, the sum of the Geometric series with infinite terms can be calculated using the formula
Therefore, if the absolute value of R is greater than equal to 1, then print “Infinite”. Otherwise, print the value as the resultant sum.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void findSumOfGP( double a, double r)
{
if ( abs (r) >= 1) {
cout << "Infinite" ;
return ;
}
double sum = a / (1 - r);
cout << sum;
}
int main()
{
double A = 1, R = 0.5;
findSumOfGP(A, R);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void findSumOfGP( double a, double r)
{
if (Math.abs(r) >= 1 )
{
System.out.print( "Infinite" );
return ;
}
double sum = a / ( 1 - r);
System.out.print(sum);
}
public static void main(String[] args)
{
double A = 1 , R = 0.5 ;
findSumOfGP(A, R);
}
}
|
Python3
def findSumOfGP(a, r):
if ( abs (r) > = 1 ):
print ( "Infinite" )
return
sum = a / ( 1 - r)
print ( int ( sum ))
if __name__ = = '__main__' :
A, R = 1 , 0.5
findSumOfGP(A, R)
|
C#
using System;
class GFG
{
static void findSumOfGP( double a, double r)
{
if (Math.Abs(r) >= 1) {
Console.Write( "Infinite" );
return ;
}
double sum = a / (1 - r);
Console.Write(sum);
}
public static void Main()
{
double A = 1, R = 0.5;
findSumOfGP(A, R);
}
}
|
Javascript
<script>
function findSumOfGP(a, r)
{
if (Math.abs(r) >= 1)
{
document.write( "Infinite" );
return ;
}
let sum = a / (1 - r);
document.write(sum);
}
let A = 1, R = 0.5;
findSumOfGP(A, R);
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1), since no extra space has been taken.
Share your thoughts in the comments
Please Login to comment...