使用C++查找佩尔数


在给定问题中,我们得到一个整数n,我们需要找到Pn,即该位置的佩尔数。众所周知,佩尔数是一个由以下公式给出的序列的一部分:−Pn = 2*Pn-1 + Pn-2

前两个起始数字为:− P0 = 0 和 P1 = 1

求解方法

现在我们将通过两种方法解决这个问题:递归和迭代。

递归方法

在这个公式中,我们将递归地应用佩尔数的公式并进行n次迭代。

示例

#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和其他语言)中编写相同的程序。

更新于:2021年11月26日

468 次浏览

开启您的职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.