C++ 幾何級數無限項求和程式
什麼是幾何級數 (GP)?
幾何級數 (GP) 是一串數字,其中每一項都是透過將前一項乘以一個常數生成的。這個常數在 GP 中被稱為公比。在本文中,我們將討論如何使用 C++ 中的不同方法來計算 GP 中無限項的和。
注意:需要記住的重要條件是,只有當公比 (r) 的絕對值小於 1 時,GP 的正有效無限和才可能存在,即 ∣r∣ < 1。
計算 GP 中無限項和的方法
以下是計算 GP 中無限項和的兩種不同方法(方法)
暴力法
我們使用迭代法來計算 GP 中無限項的和。我們初始化一個變數來儲存項的和並獲取迭代次數。我們設定第一項 a,並將當前項新增到總和中。透過將其乘以公比來更新當前項。此過程將持續到一定次數的迭代並返回 GP 的無限項之和。
步驟
- 檢查 |r| >= 1。如果為真,則返回
NAN
,因為級數不收斂。 - 初始化
sum
和currentTerm
為第一項 a。 - 使用迴圈迭代計算項的和,在預定義的最大迭代次數後停止以模擬無限項。
實現
#include <bits/stdc++.h> using namespace std; double sumOfInfiniteTermsGP(double a, double r) { if (fabs(r) >= 1) { return NAN; } double sum = 0; double currentTerm = a; // We will take the maximum number of iterations int maxIterations = 10000; // Iteratively calculate the sum of terms while (maxIterations > 0) { sum += currentTerm; currentTerm *= r; maxIterations--; } return sum; } int main() { double ans = sumOfInfiniteTermsGP(12, 0.2); if (!isnan(ans)) { cout << "The sum of infinite terms in the GP is: " << ans << endl; } else { cout << "Sum does not converge as |r| >= 1" << endl; } return 0; }
輸出
The sum of infinite terms in the GP is: 15
複雜度分析
- 時間複雜度:O(n),其中 n 是迭代次數。
- 空間複雜度:O(1),因為沒有使用額外的空間。
直接公式法
我們可以使用直接公式來找到幾何級數的無限項之和。求 GP 無限項和的公式為
GP 的無限項和 = a / (1 - r),如果 ∣r∣ < 1
步驟
- 定義一個函式,該函式採用兩個引數:第一項和公比。
- 檢查 r 的絕對值是否大於或等於 1。如果為真,則返回
NAN
,因為級數不收斂。 - 使用公式
Sum = a / (1 - r)
計算 GP 的無限項之和。 - 最後,返回總和。
實現
#include <bits/stdc++.h> using namespace std; double sumOfInfiniteTermsGP(double a, double r) { if (fabs(r) >= 1) { return NAN; } return a / (1 - r); } int main() { double ans = sumOfInfiniteTermsGP(12, 0.2); if (!isnan(ans)) { cout << "The sum of infinite terms in the GP is: " << ans << endl; } else { cout << "Sum does not converge as |r| >= 1" << endl; } return 0; }
輸出
The sum of infinite terms in the GP is: 15
複雜度分析
- 時間複雜度:O(1),因為計算是在常數時間內完成的。
- 空間複雜度:O(1),因為沒有使用額外的空間。
廣告