In the previous article we have discussed Java Program to Check Goldbach Number
In this article we are going to understand what Special number is and how we can check whether a number is Special or not in Java with examples.
Program to Check Strong Number
Strong numbers are numbers whose sum of factorial of individual digits is equal to the number itself.
Example : 145: 1!+4!+5!= 1+24+120 = 145 Special number 19: 1!+9!=1+362880=362881 Not a Special number 124: 1!+2!+4!= 1+2+24=27 Not a Special number
In the above examples the numbers 19 and 124 are not special numbers as their factorials don’t add up to the numbers. Hence 145 is the only Special number here.
Let’s see different ways to check special number.
Approach :
- Enter/Declare a number and store it .
- We calculate the factorials of each digit using a function and add them.
- If the resultant sum is the same as the entered number, then the number is said to be a Special number.
Method-1: Java Program to Check Strong Number By Using Static Value
import java.util.Scanner; public class SpecialNumber{ public static void main(String args[]) { //A number declared; int num = 145; int temp = num,remainder, sum =0; //Loop to iterate through digits and add their factorials while(temp>0) { remainder = temp%10; sum+= factorialOf(remainder); temp = temp /10; } if(sum==num) { System.out.println(num+" is a special number"); } else { System.out.println(num+" is not a special number"); } } // Function that returns the factorial of the number static int factorialOf(int num) { int prod = 1; while(num>0) { prod = prod*num; num--; } return prod; } }
Output: 145 is a special number
Method-2: Java Program to Check Strong Number By User Input Value
import java.util.Scanner; public class SpecialNumber{ public static void main(String args[]) { //Taking the number as input from the user using scanner class Scanner scan = new Scanner(System.in); System.out.print("Enter a number : "); int num = scan.nextInt(); int temp = num,remainder, sum =0; //Loop to iterate through digits and add their factorials while(temp>0) { remainder = temp%10; sum+= factorialOf(remainder); temp = temp /10; } if(sum==num) { System.out.println(num+" is a special number"); } else { System.out.println(num+" is not a special number"); } } // Function that returns the factorial of the number static int factorialOf(int num) { int prod = 1; while(num>0) { prod = prod*num; num--; } return prod; } }
Output: Case-1 Enter a number : 145 145 is a special number Case-2 Enter a number : 124 124 is a special number
Don’t miss the chance of Java programs examples with output pdf free download as it is very essential for all beginners to experienced programmers for cracking the interviews.
Related Java Programs: