Subscribe Us

Strong Number In Java

Strong Number


Java Program To Check Strong Number or Not

Strong number is a special number whose sum of the factorial of digits
is equal to the original number.


Example:
Given Number : 145
It is a Strong Nuumber.
Since: 1! + 4! + 5! = 145
1! = 1*1 = 1
4! = 1*2*3*4 = 24
5! = 1*2*3*4*5 = 120
Example:
Given Number : 125
It is Not a Strong Nuumber.
Since:
1! + 2! + 5! = 123
1! = 1*1 = 1
2! = 1*2 = 2
5! = 1*2*3*4*5 = 120

To check if a number is a Strong Number in Java
you can use the following algorithm:
  1. Read the input number.
  2. Create a copy of the input number.
  3. Initialize a variable sum to 0.
  4. While the given number is not equal to 0,perform the following steps:
    • Get the last digit of the num by using the modulo operator (%).
    • Calculate the factorial of the last digit and add it to the sum.
    • Divide the num by 10 to remove the last digit.
  5. Check if the sum is equal to the copy number.
    • If they are equal, the number is a Strong Number.
      Otherwise, it is not.
  6. Print the result.
Here is an example implementation in Java

Source Code

// Java Program To Check Strong Number Or Not ?
import java.util.*;
public class Strong
  {
    public static void main(String args[])
      {
        Scanner in = new Scanner(System.in);
        int num , Rd , fact, i, sum=0 , ncopy;
        System.out.print("Enter a Number To Check : ");
        num = in.nextInt();
        ncopy=num;
        while(num!=0)
          {
            Rd  = num % 10 ;
            fact= 1 ;
              for(i=1;i<=Rd;i++)
                 {
                   fact = fact * i ;  
                 }
            sum = sum + fact ;      
            num = num / 10 ;
          }
        if(sum==ncopy)
          System.out.print("It is a Strong Number . ");
        else
          System.out.print("It is Not a Strong Number . ");
      }
  }

Output

Sample Input :
Enter a Number To Check : 145
Sample Output:
It is a Strong Number

Sample Input :
Enter a Number To Check : 123
Sample Output:
It is Not a Strong Number