C++程序查找序列1 2 2 3 3 3 4中的第n项
在这个问题中,我们给定一个整数N。任务是在序列1 2 2 3 3 3 4…中找到第n项。
让我们举个例子来理解这个问题,
输入
N = 6
输出
3
解释
该序列到第n项为1, 2, 2, 3, 3, 3, ...
解决方案方法
解决此问题的一个简单方法是使用嵌套循环。外部for循环从1到n。内部循环从1到i(外部循环的迭代器)。对于内部循环中的每次迭代,计算序列元素的数量,并在计数等于n时返回i的值。
解决此问题的一个更有效的方法是使用模式位置。序列的元素及其在序列中的位置为:
Element 1: position 1 Element 2: position 2, 3 Element 3: position 4, 5, 6 Element 4: position 7, 8, 9, 10
对于这些值,我们可以使用序列中元素的最后一个位置创建一个序列,即,
1, 3, 6, 10, 15, 21, 28, ….
x出现在第1 + 2 + 3 + … + (x-2) + (x-1)…项中。
这可以概括为n = x*(x-1)/2
2n = x2 - x => x2 - x - 2n = 0
使用二次方程解公式求解方程,
$$x=1/2*(1+\sqrt{1+8*n)}$$
程序说明解决方案的工作原理,
示例
#include <bits/stdc++.h>
using namespace std;
int findNthTerm(int n) {
int x = (((1) + (double)sqrt(1 + (8 * n))) / 2);
return x;
}
int main(){
int n = 12;
cout<<"The series is 1, 2, 2, 3, 3, 3, 4, 4, ...\n";
cout<<n<<"th term of the series is "<<findNthTerm(n);
return 0;
}输出
The series is 1, 2, 2, 3, 3, 3, 4, 4, ... 12th term of the series is 5
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP