Peterson Number In Java Trick 2024 | topperbhai.com

Peterson Number  In Java

Peterson Number In Java Trick

What is   Peterson Number?

A number is said to be a Peterson number if the sum of factorials of each digit of the number is equal to the number itself.

For  example:- The number 145, because  the sum of factorial of each digit represent the number itself.


In this tutorial first, we will write the algorithm, then we will write the program.


Algorithm:-

Step 1:  Initialize a number (n)

Step 2:  Make a copy of (n)

Step 3:  Extract the last digit (extract) of the number

Step 4:  Find the factorial (f) of the digit

Step 5:  Add that factorial (f) to a variable (sum)

Step 6:  Repeat steps 3 to 5 until the input number becomes 0


For  example:- 

145 = 5! + 4! + 1!

     = 120 + 24 +1

     = 145


Now, I will write a simple java program to check whether the number input by the user is a peterson or not.


Basically, the logic I have implemented in this program is pretty easy to understand.


I will ask the user to enter a number then, pick each digit (Starting from the last digit) of the given number and find the factorial of that digit.


Repeat this process till the first digit then, add all factorials. Finally, I will check if the sum of factorials is equal to number or not. 



 import java.util.*;  
 class Peterson_Number  
 {  
   public static void main()  
   {  
     Scanner sc=new Scanner(System.in);  
     int n,extract,sum=0,i,f=1,copy;  
     System.out.println("Enter:");  
     n=sc.nextInt();  
     copy=n;  //Copy of n  
     while(n!=0)  //extracts digits and counts the sum of their factorials  
     {  
       extract=n%10;  
       for(i=1;i<=extract;i++)  
       {  
         f=f*i;  //calculate factorials  
       }        
       sum=sum+f;  //sum of factorials  
       f=1;  //resets value of f after finding factorial of particular digit  
       n=n/10; //reduce n  
     }  
     if(sum==copy)  
     {  
       System.out.println("It is a Peterson Number");  
     }  
     else  
     {  
       System.out.println("It is not a Peterson Number");  
     }  
   }  
 }  

 Enter:  
 145  
 It is a Peterson Number  

Post a Comment

0 Comments