C++ 程序查找级数 1, 5, 32, 288… 的第 N 项
此问题给出了整数 N,我们的任务是编写程序来查找级数 1,5, 32, 288 ... 的第 N 项。
拿个例子来理解这个问题:
输入
N = 4
输出
288
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
解释
第 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
广告