PELL NUMBER IN JAVA
AMRUHA AHMED
21st January,2024.
Pell Numbers are a sequence of integers which can be generated using the formula :
Pn=0 for n=0
Pn=1 for n=1
Pn= 2 Pn-1+Pn-2 for n>1
Pell Numbers are immensely useful in error-correction codes and cryptographic algorithms.
VARIABLES REQUIRED:- p0: to store the first term of the sequence
- p1: to store the second term of the sequence
- p2: to store the n'th term of the sequence
- ctr: to store the count of numbers printed on screen
- n: number of terms to be printed on screen
- 1.Start
- 2.Initialize the values of p0,p1,pn and ctr as 0,1,0,0 respectively
- 3.Accept the number of terms from the user and store in 'n'
- 4.If n is 0 then go to step 10 otherwise step 5
- 5.If n=1 then print p0 and go to Step 10 . Otherwise go to step 6
- 6.If n=2 then print p0 and p1 and go to step 10 . Otherwise go to step 7
- 7.Display the values of p0 and p1
- 8.Update value of ctr to 2
- 9.While ctr is less than n, repeat the following steps, otherwise go to step 10
- (i) calculate pn as 2*p1+p0
- (ii) display pn
- (iii)update values of p0 as p1 and p1 as pn
- (iv) increment ctr by 1
- 10.Stop
PROGRAM:
import java.util.*;
class pellnumber {
Scanner ob = new Scanner(System.in);
void main() {
int p0 = 0; //first term of the sequence
int p1 = 1; //second term of the sequence
int pn = 0; //n'th term of the sequence
int ctr = 0; //to store the count of numbers printed on screen
int n; //number of terms to be printed
System.out.print("\n Enter the number of terms:");
n = ob.nextInt();
System.out.println("\n The pell numbers are ....\n");
if (n == 0) {
System.out.print("\n Wrong input");
System.exit(1);
} else if (n == 1) {
System.out.print(" " + p0);
System.exit(0);
} else if (n == 2) {
System.out.print(" " + p0 + " " + p1);
System.exit(0);
} else // for n>2
{
System.out.print(" " + p0 + " " + p1);
ctr = 2;
while (ctr < n) // to generate the next pell numbers
{
pn = 2 * p1 + p0; //calculating the n'th pell number
System.out.print(" " + pn);
//updating values of p0 and p1 for the next iteration
p0 = p1;
p1 = pn;
ctr++; //updating count of terms printed
}
}
}
}
DRY RUN:
Supposing 'n' is given as 5 and p0=0, p1=1, pn=0 and ctr=0 initially then:
OUTPUT:
Enter the number of terms: 5
The pell numbers are ....
0 1 2 5 12