Find the Pell Number using C++

C++Server Side ProgrammingProgramming

In the given problem, we are given an integer n we need to find Pn, i.e., the pell number in that position. Now, as we know, pell number is a part of a series given by this formula −Pn = 2*Pn-1 + Pn-2

With first two starting numbers − P0 = 0 and P1 = 1

Approach to find The Solution

Now we will solve this problem by two approaches: recursive and iterative.

Recursive Approach

In this formula, we will recursively apply the formula of Pell Number and do n iterations.

Example

#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;
}

Output

70

Explanation of the above code

In this approach, we use recursion by calling pell(n-1) && pell(n-2) till n becomes less than or equal to 2 as we know the pell numbers till 2 are the same as the given number. The overall time complexity of the above program is O(N), where N is the given number.

Iterative Approach

In this approach, we will use the same formula as above but calculate the number using a for loop instead of a recursive function.

Example

#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;
}

Output

70

Explanation of the above code

In the given program, we are traversing from 2 till n and simply updating the values for pn-2 to pn-1 and pn-1 to pn till we reach n.

Conclusion

In this article, we solved the problem of finding the Nth pell number using recursion and iteration. We also learned the C++ program for this problem and the complete approach ( Normal and efficient ) by which we solved this problem. We can write the same program in other languages such as C, java, python, and other languages.

raja
Updated on 26-Nov-2021 07:29:58

Advertisements