Strong number or not using Java

Strong number or not using java :

 

Strong Number is the number whose sum of factorial of the digits in any number is equal to the given number. 

Simply, if we have  a number then firstly calculate the factorial of each digit of the number and then calculate the sum of factorial of each digit.

Let us consider an example :

Suppose we have a number 145 then,

  • Factorial of all digits –

Factorial of 1 = 1 ;

Factorial of 4 = 24 ;

Factorial of 5 = 120 ;

  • Sum of Factorial of all digits –

1 + 24 + 120 = 145 ;

Here the calculated result is equal to the given number ;

So, 145 is a Strong Number. 

In this article we will create a java program to check whether the given number is a Strong number or not.

Strong number or not using Java

Working :

Step 1 : Ask the user to enter a number.

Step 2 : Declare three variables, one for storing factorial, second for storing sum and third for storing the copy of the given number so that the changes we make that should not reflect in the original number.

Step 3 : Use a loop till number is not equal to 0.

Step 4 : Continuously pick out last digit of the number till the number exist.

Step 5 : Use a loop to calculate factorial of each digit.

Step 6 : Calculate and store the sum and change the value of number accordingly.

Step 7 : Repeat Steps 3 to 6 till condition for loop does not get false.

Step 8 : Compare that whether the sum is equal to the given number or not.

  • If this gets true , then the given number is Strong Number.
  • Else the number is not a Strong Number. 

Code in Java :

//Java program to check whether a number is a strong number or not
import java.util.Scanner;
public class strong_number_or_not
{
public static void main(String[] args)
{
//scanner class declaration
Scanner sc = new Scanner(System.in);
//input from user
System.out.print("Enter a number : ");
int number = sc.nextInt();
int fac,sum = 0;
int n = number;
while(n != 0)
{
fac = 1;
int r = n % 10;
//calculating factorial of r
for(int i = r ; i >= 1 ; i--)
fac = fac * i;
//storing sum of factorial of all digits of the number
sum = sum + fac;
n=n/10;
}
//condition for strong number
if(sum == number)
System.out.println("Strong Number");//display the result
else
System.out.println("Not a Strong Number");
//closing scanner class(not compulsory, but good practice)
sc.close();
}
}

Output :

Enter a number : 145
Strong Number


Enter a number : 123
Not a Strong Number