C++程式查詢數列1 2 2 4 4 4 4 8 8 8 8 8 8 8 8 …的第n項。
在這個問題中,我們給定一個整數N。我們的任務是建立一個程式來查詢數列1、2、2、4、4、4、4、8、8、8、8、8、8、8、8…的第N項。
讓我們舉個例子來理解這個問題,
輸入
N = 7
輸出
4
解決方案方法
解決這個問題的一個簡單方法是使用迴圈來查詢第n個位置的項。這些項將在每次迭代後透過加倍來更新。並將其新增到項計數器中。
程式說明我們解決方案的工作原理,
示例
#include <iostream> using namespace std; int calcNthTerm(int N) { int termCounter = 0, termValue = 1; while (termCounter < N) { termCounter += k; termValue *= 2; } return termValue / 2; } int main() { int N = 10; cout<<N<<"th term of the series is "<<calcNthTerm(N); return 0; }
輸出
10th term of the series is 8
有效方法
解決這個問題的一個有效方法是找到該數列的通項公式。
Here, are terms and their last index, 1 -> last index = 1. 2 -> last index = 3. 4 -> last index = 7. 8 -> last index = 15. . . T(N) -> last index = 2*(T(N)) - 1 Also, T(N) is always of a power of 2, i.e. T(N) = 2m 2m lies in the series till the index 2m+1-1.
為了找到該項,我們可以使用N計算2(m) - 1的值。
這使得2m - 1 < N。
2m - 1 < N So, m < log2(N + 1)
程式說明我們解決方案的工作原理,
示例
#include <iostream> #include <math.h> using namespace std; int calcNthTerm(int N) { return ( pow(2, (floor)(log(N + 1) / log(2)) ) ) ; } int main() { int N = 10; cout<<N<<"th term of the series is "<<calcNthTerm(N); return 0; }
輸出
10th term of the series is 8
廣告