C++ 程序查找 1, 6, 18, 40, 75 等数列的第 N 项。
在这个问题中,我们给定一个整数 N。我们的任务是创建程序以查找1,6,18,40,75 等数列的第 N 项。
我们举个例子来理解这个问题:
输入
N = 4
输出
40
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 * 5 ) / 2 = 40
解决方案方法
解决该问题的一个简单方法是使用该序列第 n 项的一般公式。其公式为:
Nth term = ( N * N * (N + 1) ) / 2
说明我们解决方案工作的程序:
示例
#include <iostream> using namespace std; int calcNthTerm(int N) { return ( (N*N*(N+1))/2 ); } int main() { int N = 5; cout<<N<<"th term of the series is "<<calcNthTerm(N); return 0; }
输出
5th term of the series is 75
广告