在系列 7、15、32、… 中找到第 n 項的 C++ 程式
在這個問題中,我們給定了一個整數 N。任務是在系列 7、15、32 中找到第 n 項...
我們舉個例子來理解這個問題,
輸入
N = 6
輸出
281
說明
到第 n 項的系列是 7、15、32、67、138、281
解決方案方法
解決這個問題的關鍵在於解碼該系列。你可以看到該系列是系列的混合。
減去的值,
T(2) - T(1) = 15 - 7 = 8 T(3) - T(2) = 32 - 15 = 17 So, T(2) = 2*T(1) + 1 T(3) = 2*T(2) + 2 T(n) = 2*T(n-1) + (n-1)
因此,第 n 項的值是使用最後一項找到的。為了找到這些值,我們將從 1 到 n 進行迴圈並找到系列的每個值。
程式來說明我們的解決方案的工作原理,
示例
#include <iostream>
using namespace std;
int findNthTerm(int n) {
if (n == 1)
return 7;
int termN = 7;
for (int i = 2; i <= n; i++)
termN = 2*termN + (i - 1);
return termN;
}
int main(){
int n = 12;
cout<<"The series is 7, 15, 32, 67...\n";
cout<<n<<"th term of the series is "<<findNthTerm(n);
return 0;
}輸出
The series is 7, 15, 32, 67... 12th term of the series is 18419
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP