Strong Number in Java

Definition of Strong Number in Java

A strong number is a special number that can be defined as an addition of factorial of each digit of the number, which is equal to the number itself. To better understand the concept of a strong number, have a look at the below example. 

The number 145 is a strong number. This is because if we add the factorials of each digit of this number, you will get the number, which is 145 itself, as the sum. 

1! + 4! + 5! = 1 + 24 + 120 = 145.

Strong Number in Java


Logic for Checking Strong Number

  • Take a user-defined number or a number as an input from the user. Store this number in a user-defined variable. Now copy this number to another temporary user-defined variable. This variable will be used for calculation purposes. You can name the user-defined variable as ‘n’ and the temporary variable as ‘temp_n’.
  • Now initialize another variable that will store the sum of factorial digits. You can name this variable as ‘total’.
  • You will also need to find the last digit of the given number ‘n’. Store this result in a variable that will store the result, say ‘lastdig = n % 10’.
  • Now you can find the factorial of ‘lastdig’. Now you can store the factorial of this number and name it as ‘fact_n’.
  • Once this is done, you can add the factorial to ‘total’. This can be done by using total = total + fact_n.
  • Now you can remove the last digit from ‘n’ as it will not be required any further
  • Now repeat the steps from step 3 to step 6 until the condition n > 0 is satisfied.
  • You can use a loop for this. It can be used to check the condition of a strong number. If the condition total == temp_n is satisfied, then the given number is a strong number, else it is not.

Code to check Strong Number in java.

// Java program for Strong Number
import java.util.Scanner;

public class StrongNumber1 {
	private static Scanner sc;
	public static void main(String[] args) 
	{
		int Number, Temp, Reminder, Sum = 0, i, Factorial;
		sc = new Scanner(System.in);
		
		System.out.print(" Please Enter any Number : ");
		Number = sc.nextInt();		
		
		Temp = Number;
		while( Temp > 0)
		{
			Factorial = 1; 
			i = 1; 
		    Reminder = Temp % 10;
		    while (i <= Reminder)
		    {
		     	Factorial = Factorial * i;
		     	i++;
		    }
		    System.out.println(" The Factorial of " + Reminder + "  =  " + Factorial);
		     Sum = Sum + Factorial;
		     Temp = Temp /10;
		}
		
		System.out.println(" The Sum of the Factorials of a Given Number " + Number + " =  " + Sum);
		
		if ( Number == Sum )
		{
			System.out.println("\n " + Number + " is a Strong Number");
		}
		else
		{
		   System.out.println("\n " + Number + " is Not a Strong Number");
		}
	}
}

Comments