C++程式:求給定序列的第N項
在這個問題中,我們給定一個數字N。我們的任務是建立一個C++程式來查詢給定序列中的第N項。
問題描述
求以下序列的和:
1, 1, 2, 3, 4, 9, 8, 27, 16, 81, 32, 243, 64, 729, 128, 2187, 256, ... N項
我們將找到該序列的通項公式。
讓我們舉個例子來理解這個問題:
示例1
輸入
N = 6
輸出
9
示例2
輸入
N = 13
輸出
64
解決方案
為了解決這個問題,我們需要仔細觀察這個序列。它是一個混合序列,這種型別的序列最初很難識別,但稍後處理起來就容易了。
該序列是混合型別的序列,
在偶數位上,序列的索引是3的冪序列。
在奇數位上,序列的索引是2的冪序列。
通項公式如下:
T_{N}=2^{N/2}, 如果N是奇數。
3^{N/2}, 如果N是偶數。
示例
#include <iostream> #include <math.h> using namespace std; int findLCM(int a, int b) { int LCM = a, i = 2; while(LCM % b != 0) { LCM = a*i; i++; } return LCM; } int findNTerm(int N) { if(N%2 == 0){ return pow(3, ((N-1)/2)); } else return pow(2, (N/2)); } int main() { int N = 9; cout<<N<<"th term of the series is "<<findNTerm(N)<<endl; N = 14; cout<<N<<"th term of the series is "<<findNTerm(N); }
輸出
9th term of the series is 16 14th term of the series is 729
廣告