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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP