Check if a number is special or not in Java
Today we will how to check whether a number is a Special number or not in Java.
But before that, we should know what is a special number.
A special number is a number such that the sum of its digit’s factorial is equal to the number itself.
Sounds confusing?
Let’s take an example to get a clear idea about a special number.
Example: 145
1! + 4! + 5! =145
5!= 5*4*3*2*1=120
4!=4*3*2*1=24
1!=1
145+24+1=145
Now we know what is a special number, so let’s start by learning how to find factorial of a method.
int fact(int n) { if(n==1 || n==0) { return 1; } else { return n*fact(n-1); } }
In the above code, we are using the recursion approach, that is, a function calling itself.
If you are not comfortable with recursion you can use the simple way of finding factorial by multiplying the number with its predecessor until 1 comes.
Now let’s look at the complete code:
class test { int fact(int n) { if(n==1 || n==0) { return 1; } else { return n*fact(n-1); } } } public class MyClass { public static void main(String args[]) { test t1=new test(); int n=145; int num=n; int res=0; int rem; while(n>0) { rem=n%10; res=res+t1.fact(rem); n=n/10; } if(res==num) { System.out.println("Number is special"); } else { System.out.println("Number is Not special"); } } }
The above program when executed will give the following output:
Number is special
Hope this helped you out. We are able to check if a number is special or not with Java programming.
Happy Coding.
Also Read:
Leave a Reply