C++程式找出數列5, 2, 13, 41,…的第n項
在這個問題中,我們給定一個整數N。我們的任務是建立一個程式來查詢數列5, 2, 19, 13, 41, 31, 71, 57…的第N項。
讓我們舉個例子來理解這個問題:
輸入
N = 5
輸出
41
解釋
該數列為:5, 2, 19, 13, 41, …
解決方案
解決這個問題的一個簡單方法是使用該數列第n項的通用公式。該數列對於奇數和偶數的值有不同的公式。
第N項由下式給出:
Nth term = (N-1)^2 + N, if N is even i.e N%2 == 0 Nth term = (N+1)^2 + N, if N is odd i.e N%2 != 0
程式演示了我們解決方案的工作原理:
示例
#include <iostream> using namespace std; int calcNthTerm(int N) { if (N % 2 == 0) return ( ( (N - 1)*( N - 1) ) + N ) ; return ( ( (N + 1)*( N + 1) ) + N ) ; } int main() { int N = 7; cout<<N<<"th term of the series is "<<calcNthTerm(N); return 0; }
輸出
6th term of the series is 258
廣告