
在给定的问题中,我们得到一个整数 n,我们需要找到 Pn,即该位置的咒语编号。现在,正如我们所知,拼写数是由以下公式给出的序列的一部分 -Pn = 2*Pn-1 + Pn-2
前两个起始数字 - P0 = 0 和 P1 = 1
现在我们将通过两种方法来解决这个问题:递归和迭代。
在这个公式中,我们将递归地应用公式Pell Number 并进行 n 次迭代。
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
using namespace std;
int pell(int n) {
if(n <= 2)
return n;
return 2*pell(n-1) + pell(n-2);
}
int main() {
int n = 6; // given n
cout << pell(n) <<"\n"; // Pell number at that position.
return 0;
}70
在这种方法中,我们通过调用 pell(n-1) && pell(n-2) 来使用递归,直到 n 小于或等于 2,因为我们知道直到 2 的拼写数字与给定数字相同。上述程序的总体时间复杂度为O(N),其中N是给定的数字。
在这种方法中,我们将使用与上面相同的公式,但使用 for 循环而不是递归函数来计算数字。
#include <iostream>
using namespace std;
int main() {
int n = 6; // given n.
int p0 = 0; // initial value of pn-2.
int p1 = 1; // initial value of pn-1.
int pn; // our answer.
if(n <= 2) // if n <= 2 we print n.
cout << n <<"\n";
else {
for(int i = 2; i <= n; i++) { // we are going to find from the second number till n.
pn = 2*p1 + p0;
p0 = p1; // pn-1 becomes pn-2 for new i.
p1 = pn; // pn becomes pn-1 for new i.
}
cout << pn << "\n";
}
return 0;
}70
在给定的程序中,我们从 2 遍历到 n,并简单地将 pn-2 的值更新为 pn-1,将 pn-1 的值更新为 pn,直到达到 n .
在本文中,我们使用递归和迭代解决了查找第 N 个咒语编号的问题。我们还学习了解决这个问题的C++程序以及解决这个问题的完整方法(正常且高效)。我们可以用其他语言编写相同的程序,例如C、java、python等语言。
以上就是使用C++找到Pell数的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号