CODING JOY

The stunning potpourri of coding and mundane life

PELL NUMBER IN JAVA



AMRUHA AHMED
21st January,2024.


blog1

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: ALGORITHM:


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
                                }
                            }
                    
                        }
                    }                   
             
         
CODE COPIED

DRY RUN:


Supposing 'n' is given as 5 and p0=0, p1=1, pn=0 and ctr=0 initially then: blog1

OUTPUT:

Enter the number of terms: 5

The pell numbers are ....

0 1 2 5 12