Pell Number in Java
In this section, we will learn what is Pell number and also create Java programs to check if the given number is a Pell number or not. The Pell number program frequently asked in Java coding interviews and academics.
Pell Number
It is a sequence or series of numbers that starts with 0 and 1, and subsequent numbers are the sum of twice the previous Pell number and the Pell number before that. It is an OEIS sequence A000129. Sometimes it is also known as lambda numbers. It is a recursively defined sequence similar to the Fibonacci sequence. We can represent the Pell sequence mathematically, as follows:
Where n>1.
A Pell prime is a Pell number that is prime. The first few Pell primes are 2, 5, 29, 5741, 33461, 44560482149, 1746860020068409, 68480406462161287469, etc. It is an OEIS sequence A086383.
It can be used to find square triangular numbers, to construct integer approximations to the right isosceles triangle, and to solve certain combinatorial enumeration problems.
Pell Number Example
Let’s see how the Pell series is generated.
We know the first and second terms of the series are 0 and 1. On the basis of these two terms, we can calculate the next Pell number.
P0 = 0
P1 = 1
P2 = 1 * 2 + 0 = 2
P3 = 2 * 2 + 1 = 5
P4 = 5 * 2 + 2 = 12
P5 = 12 * 2 + 5 = 29
P6 = 29 * 2 + 12 = 70
P7 = 70 * 2 + 29 = 169
P8 = 169 * 2 + 70 = 408
P9 = 408 * 2 + 169 = 985
P10 = 985 * 2 + 408 = 2378
We have calculated the first ten terms of the Pell series. Similarly, we can calculate other terms such as 5741, 13860, 33461, 80782, 195025, 470832, 1136689, 2744210, 6625109, 15994428, 38613965, 93222358, 225058681, 543339720, 1311738121, 3166815962, 7645370045, 18457556052, 44560482149, 107578520350, 259717522849.
Steps to Find Pell number
- Initialize the first two terms of the series as P0=0 and P1=1.
- In order to calculate the third (P2) term, do the following:
Multiply the previous term (P1) by 2 and add the Pell number before that i.e. P0. Hence, we get the third term of the series. - Repeat step 2 up to the number of terms we want to calculate.
Let’s implement the above steps in a Java program.
Pell Number Java Program
Using Recursion Approach
PellNumberExample1.java
Output:
The 7-th term of the series is: 169
Let’s see another approach to find the Pell numbers using an iterative approach.
Using Iterative Approach
PellNumberExample2.java
Output:
The 17-th term of the series is: 1136689
Print All Pell Numbers up to Specified Limit
PellNumberExample3.java
Output:
Enter the limit: 20 First 20 Pell numbers are: 1, 2, 5, 12, 29, 70, 169, 408, 985, 2378, 5741, 13860, 33461, 80782, 195025, 470832, 1136689, 2744210, 6625109, 15994428