C++程序查找数列1 2 2 4 4 4 4 8 8 8 8 8 8 8 8 …的第n项。
在这个问题中,我们给定一个整数N。我们的任务是创建一个程序来查找数列1、2、2、4、4、4、4、8、8、8、8、8、8、8、8…的第N项。
让我们举个例子来理解这个问题,
输入
N = 7
输出
4
解决方案方法
解决这个问题的一个简单方法是使用循环来查找第n个位置的项。这些项将在每次迭代后通过加倍来更新。并将其添加到项计数器中。
程序说明我们解决方案的工作原理,
示例
#include <iostream>
using namespace std;
int calcNthTerm(int N) {
int termCounter = 0, termValue = 1;
while (termCounter < N) {
termCounter += k;
termValue *= 2;
}
return termValue / 2;
}
int main() {
int N = 10;
cout<<N<<"th term of the series is "<<calcNthTerm(N);
return 0;
}输出
10th term of the series is 8
有效方法
解决这个问题的一个有效方法是找到该数列的通项公式。
Here, are terms and their last index, 1 -> last index = 1. 2 -> last index = 3. 4 -> last index = 7. 8 -> last index = 15. . . T(N) -> last index = 2*(T(N)) - 1 Also, T(N) is always of a power of 2, i.e. T(N) = 2m 2m lies in the series till the index 2m+1-1.
为了找到该项,我们可以使用N计算2(m) - 1的值。
这使得2m - 1 < N。
2m - 1 < N So, m < log2(N + 1)
程序说明我们解决方案的工作原理,
示例
#include <iostream>
#include <math.h>
using namespace std;
int calcNthTerm(int N) {
return ( pow(2, (floor)(log(N + 1) / log(2)) ) ) ;
}
int main() {
int N = 10;
cout<<N<<"th term of the series is "<<calcNthTerm(N);
return 0;
}输出
10th term of the series is 8
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP