C++ 程式查詢級數 1, 5, 32, 288… 的第 N 項
此問題給出了整數 N,我們的任務是編寫程式來查詢級數 1,5, 32, 288 ... 的第 N 項。
拿個例子來理解這個問題:
輸入
N = 4
輸出
288
解釋
第 4 項 − (4^4) + (3^3) + (2^2) + (1^1) = 256 + 27 + 4 + 1 = 288
解決方案方法
解決問題的簡單方法是使用該級數第 n 項的通用公式。該公式為:
第 n 項 = ( N^N ) + ( (N-1)^(N-1) ) + … + ( 2^2 ) + ( 1^1 )
程式說明了我們解決方案的工作原理:
示例
#include <iostream> using namespace std; int calcNthTerm(int N) { if (N <= 1) return 1; int factorial = 1; for (int i = 1; i < N; i++) factorial *= i; return factorial; } int main() { int N = 8; cout<<N<<"th term of the series is "<<calcNthTerm(N); return 0; }
輸出
8th term of the series is 5040
廣告