How to check where a number is special number in Java

1 Answer

0 votes
// Special number = sum of the factorial of digits is equal to the number
 
public class MyClass {
    static int factorial(int num) {
        int fact = 1;
         
        while (num != 0) {
            fact = fact * num;
            num--;
        }
         
        return fact;
    }
 
    static boolean isSpecial(int num) {
        int sum = 0, tmp = num;
         
        while (tmp != 0) {
            sum += factorial(tmp % 10);
            tmp = tmp / 10;
        }
         
        return sum == num;
    }
    public static void main(String args[]) {
        int num = 145; // 1! + 4! + 5! = 1 + 24 + 120 = 145
     
        if (isSpecial(num)) {
            System.out.println("yes");
        }
        else {
            System.out.println("no");
        }
    }
}
 
 
 
 
/*
run:
 
yes
 
*/

 



answered Nov 25, 2023 by avibootz
edited Nov 26, 2023 by avibootz

Related questions

1 answer 116 views
1 answer 130 views
1 answer 150 views
1 answer 112 views
1 answer 101 views
1 answer 114 views
1 answer 146 views
...