📜  无限几何级数 (GP) 的总和

📅  最后修改于: 2022-05-13 01:56:07.611000             🧑  作者: Mango

无限几何级数 (GP) 的总和

给定两个整数AR ,表示几何序列的第一项和公比,任务是找到由给定的第一项和公比形成的无限几何级数之和。

例子:

方法:可以根据以下观察解决给定的问题:

  • 如果R的绝对值大于等于 1,则和将是无限的。
  • 否则,可以使用以下公式计算具有无限项的几何级数之和

因此,如果R的绝对值大于等于 1,则打印“Infinite” 。否则,打印值\frac{A}{(1 - R)}         作为结果总和。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to calculate the sum of
// an infinite Geometric Progression
void findSumOfGP(double a, double r)
{
    // Case for Infinite Sum
    if (abs(r) >= 1) {
        cout << "Infinite";
        return;
    }
 
    // Store the sum of GP Series
    double sum = a / (1 - r);
 
    // Print the value of sum
    cout << sum;
}
 
// Driver Code
int main()
{
    double A = 1, R = 0.5;
    findSumOfGP(A, R);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to calculate the sum of
// an infinite Geometric Progression
static void findSumOfGP(double a, double r)
{
     
    // Case for Infinite Sum
    if (Math.abs(r) >= 1)
    {
        System.out.print("Infinite");
        return;
    }
 
    // Store the sum of GP Series
    double sum = a / (1 - r);
 
    // Print the value of sum
    System.out.print(sum);
}
 
// Driver Code
public static void main(String[] args)
{
    double A = 1, R = 0.5;
    findSumOfGP(A, R);
}
}
 
// This code is contributed by 29AjayKumar


Python3
# Python3 program for the above approach
 
# Function to calculate the sum of
# an infinite Geometric Progression
def findSumOfGP(a, r):
   
    # Case for Infinite Sum
    if (abs(r) >= 1):
        print("Infinite")
        return
 
    # Store the sum of GP Series
    sum = a / (1 - r)
 
    # Print the value of sum
    print(int(sum))
 
# Driver Code
if __name__ == '__main__':
    A, R = 1, 0.5
    findSumOfGP(A, R)
 
# This code is contributed by mohit kumar 29.


C#
// C# program for the above approach
using System;
class GFG
{
   
    // Function to calculate the sum of
    // an infinite Geometric Progression
    static void findSumOfGP(double a, double r)
    {
       
        // Case for Infinite Sum
        if (Math.Abs(r) >= 1) {
            Console.Write("Infinite");
            return;
        }
 
        // Store the sum of GP Series
        double sum = a / (1 - r);
 
        // Print the value of sum
        Console.Write(sum);
    }
 
    // Driver Code
    public static void Main()
    {
        double A = 1, R = 0.5;
        findSumOfGP(A, R);
    }
}
 
// This code is contributed by ukasp.


Javascript


输出:
2

时间复杂度: O(1)
辅助空间: O(1)