Strong Number in Java


This program checks if a given number is a strong number or not. A strong number is a number whose sum of factorials of each digit is equal to the original number.

  • The program first prompts the user to enter a number. It then takes the input and saves it in the variable num. The variable originalNum is used to store the original value of num for later comparison.
  • Next, the program enters a while loop that runs until num is greater than 0. Within the loop, the variable rem is used to store the remainder of num divided by 10 (i.e., the last digit of num).
  • Then, a for loop is used to calculate the factorial of rem, which is stored in the variable fact. The factorial is calculated by starting with i as 1 and multiplying fact by i in each iteration until i reaches rem. The result is then added to the variable sum.
  • After the for loop finishes, num is divided by 10, which drops the last digit, and the loop continues with the next digit. This process continues until all digits have been processed.
  • Finally, the program checks if sum is equal to originalNum. If they are equal, the program prints that the original number is a strong number. Otherwise, it prints that the original number is not a strong number.

Note that this program assumes that the input is a positive integer. If the input is not a positive integer, the program behavior is undefined.

Source Code

import java.util.Scanner;
 
public class strong {
    //Write a program to check the given number is Strong number or not.
    public static void main(String args[])
    {
        int num,originalNum,rem,fact,i,sum=0;
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a number : ");
        num=in.nextInt();
        originalNum=num;
        while (num>0)//145>0  14>0 1>0
        {
            rem=num%10;
            //System.out.println("Reminder : "+rem);
            fact=1;
            for(i=1;i<=rem;i++){
                fact*=i;//fact=fact*i
            }
            //System.out.println("fact : "+fact);
            sum+=fact;
            num=num/10;
        }
        if (sum == originalNum) {
            System.out.println(originalNum + " is STRONG NUMBER");
        } else {
            System.out.println(originalNum + " is not a STRONG NUMBER");
        }
    }
}
 

Output

Enter a number :
145
145 is STRONG NUMBER
Enter a number :
234
234 is not a STRONG NUMBER
To download raw file Click Here

Basic Programs