C++程序找出数列9, 33, 73, 129…中的第n项
在这个问题中,我们给定一个整数N。任务是找到数列9, 33, 73, 129…中的第n项。
让我们举个例子来理解这个问题:
输入
N = 4
输出
129
解释
该数列到第n项是 9, 33, 73, 129…
解决方案
问题的解决方案在于找到该数列的第n项。我们将用数学方法找到它,然后将通项公式应用到我们的程序中。
首先,让我们通过将数列向后移动一位来进行相减。
Sum = 9 + 33 + 73 + … + t(n-1) + t(n) - Sum = 9 + 33 + 73 + …. + t(n-1) + t(n) 0 = 9 + ((33- 9) + (73 - 33) + … + (tn) - t(n-1)) - t(n) t(n) = 9 + (24 + 40 + 56 + …. ) 24 + 40 + 56 + …. is an A.P. series with common difference 16.
这使得通项为:
t(n) = 9 + [ ((n-1)/2)*(2*(24) + (n-1-1)*16) ]
$$t(n)=9+[\left(\frac{n-1}{2}\right)*((2*24)+(n-2)*16)]$$ $$t(n)=9+[\left(\frac{n-1}{2}\right)*((2*24)+(n-2)*8)]$$
t(n) = 9 + [(n - 1) * ((24) + (n - 2) * 8)]
t(n) = 9 + [(n - 1) * (24 + 8n - 16)]
t(n) = 9 + [(n - 1) * (8 + 8n)]
t(n) = 9 + 8 * [(n - 1) * (n + 1)]
t(n) = 9 + 8 * [n2 - 12]
t(n) = 9 + 8 * n2 - 8
t(n) = 8 * n2 + 1
程序说明我们解决方案的工作原理:
示例
#include <iostream>
using namespace std;
int findNthTerm(int n) {
return (8*n*n) + 1 ;
}
int main(){
int n = 12;
cout<<"The series is 9, 33, 73, 129...\n";
cout<<n<<"th term of the series is "<<findNthTerm(n);
return 0;
}输出
The series is 9, 33, 73, 129... 12th term of the series is 1153
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP