已知等比數列的第 M 項和第 N 項,求第 P 項 (C++ 實現)
本題給定五個值 m、n、第 m 項、第 n 項和 p。我們的任務是:已知等比數列的第 M 項和第 N 項,求第 P 項。
對於一個等比數列,我們已知第 m 項和第 n 項的值。利用這些值,我們需要找到數列的第 p 項。
讓我們來看一個例子來理解這個問題:
輸入
m = 7, mthTerm = 1458, n = 10, nthterm = 39366, p = 3
輸出
18
解決方案
這裡,我們給定一個等比數列。假設等比數列為:
GP = a , a*r , a*(r2), a*(r3) ….
第 T 項的公式為
Tth Term = a * r(T-1)
現在,我們已知第 n 項和第 m 項:
mth term = a * (r ^ (m-1)) nth term = a * (r ^ (n-1))
將兩個等式相除,我們得到:
mth term / nth term = (r ^(m - n))
使用這個等式,我們可以找到 r 的值,然後可以使用第 m 項的值來找到 a:
mth term = a * (r^(m-1))
然後在找到 a 和 r 的值後,可以使用以下公式輕鬆找到第 p 項的值:
pth term = a * (r^(p-1))
程式演示了我們解決方案的工作原理:
示例
#include <cmath> #include <iostream> using namespace std; double findRinGP(double m, double n, double mth, double nth) { if (m < n) return pow(nth / mth, 1.0 / (n - m)); return pow(mth / nth, 1.0 / (m - n)); } double findTermGP(int m, int n, double mth, double nth, int p) { double r = findRinGP(m, n, mth, nth); double a = mth / pow(r, (m - 1)); return ( a * pow(r, (p - 1)) ); } int main() { int m = 7, n = 10, p = 5; double mth = 1458, nth = 39366; cout<<"The "<<p<<"th of the series is "<<findTermGP(m, n, mth, nth, p); return 0; }
輸出
The 5th of the series is 162
廣告