计算无限算术几何序列之和的程序
给定三个整数A 、 D和R代表无限算术-几何级数的第一项、公差和公比,任务是找到给定无限算术-几何级数的总和,使得R的绝对值总是小于1 。
例子:
Input: A = 0, D = 1, R = 0.5
Output: 0.666667
Input: A = 2, D = 3, R = -0.3
Output: 0.549451
方法:算术几何序列是几何级数级数与等差级数级数的相应项逐项相乘的结果。该系列由:
a, (a + d) * r, (a + 2 * d) * r2, (a + 3 * d) * r3, …, [a + (N − 1) * d] * r(N − 1).
算术几何级数的第N项由下式给出:
=>
算术几何级数的总和由下式给出:
=>
where, |r| < 1.
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to find the sum of the
// infinite AGP
void sumOfInfiniteAGP(double a, double d,
double r)
{
// Stores the sum of infinite AGP
double ans = a / (1 - r)
+ (d * r) / (1 - r * r);
// Print the required sum
cout << ans;
}
// Driver Code
int main()
{
double a = 0, d = 1, r = 0.5;
sumOfInfiniteAGP(a, d, r);
return 0;
}
Java
// Java program for the above approach
class GFG{
// Function to find the sum of the
// infinite AGP
static void sumOfInfiniteAGP(double a, double d,
double r)
{
// Stores the sum of infinite AGP
double ans = a / (1 - r) +
(d * r) / (1 - r * r);
// Print the required sum
System.out.print(ans);
}
// Driver Code
public static void main(String[] args)
{
double a = 0, d = 1, r = 0.5;
sumOfInfiniteAGP(a, d, r);
}
}
// This code is contributed by 29AjayKumar
Python3
# Python3 program for the above approach
# Function to find the sum of the
# infinite AGP
def sumOfInfiniteAGP(a, d, r):
# Stores the sum of infinite AGP
ans = a / (1 - r) + (d * r) / (1 - r * r);
# Print the required sum
print (round(ans,6))
# Driver Code
if __name__ == '__main__':
a, d, r = 0, 1, 0.5
sumOfInfiniteAGP(a, d, r)
# This code is contributed by mohit kumar 29.
C#
// C# program for the above approach
using System;
class GFG
{
// Function to find the sum of the
// infinite AGP
static void sumOfInfiniteAGP(double a, double d,
double r)
{
// Stores the sum of infinite AGP
double ans = a / (1 - r) + (d * r) / (1 - r * r);
// Print the required sum
Console.Write(ans);
}
// Driver Code
public static void Main()
{
double a = 0, d = 1, r = 0.5;
sumOfInfiniteAGP(a, d, r);
}
}
// This code is contributed by ukasp.
Javascript
输出
0.666667
时间复杂度: O(1)
辅助空间: O(1)