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