WAP to check a Special number
Answers
Solution.
The given code is written in Java.
import java.util.*;
public class IsSpecial{
static int fact(int n){
if(n==0)
return 1;
return n * fact(n-1);
}
public static void main(String s[]){
int n,a,sum=0;
System.out.print("Enter a number: ");
n=a=(new Scanner(System.in)).nextInt();
for(;a!=0;a/=10)
sum+=fact(a%10);
if(sum==n)
System.out.println("Number is a special number.");
else
System.out.println("Number is not a special number.");
}
}
A special number is such a number whose sum of factorial of digits is equal to the number itself.
For example,
> 145 = 1! + 4! + 5!
Factorial of a number (n) means the product of all numbers from 1 to n.
> 5! = 1 × 2 × 3 × 4 × 5 and so on.
Logic.
- Accept the number.
- Calculate factorial of the digits present in the number. Add them up and store the sum in variable 'sum'.
- Check if sum is equal to the entered number or not. If true, number is special number or not.
See attachment for output.