How to find all the numbers that are equal to the sum of the factorials of their digits in Java

1 Answer

0 votes
import java.util.ArrayList;
import java.util.List;

// Example: 145 = 1! + 4! + 5! = 1 + 24 + 120 = 145

public class DigitFactorialFinder {

    // Function to compute the factorial of a number
    private static int factorial(int n) {
        int fact = 1;

        for (int i = 2; i <= n; i++) {
            fact *= i;
        }

        return fact;
    }

    // Function to find all numbers equal to the sum of the factorials of their digits
    private static void findDigitFactorialNumbers() {
        // Precompute factorials of digits 0-9
        List<Integer> factorials = new ArrayList<>();
        for (int i = 0; i <= 9; i++) {
            factorials.add(factorial(i));
        }

        // Define an upper limit (7 * 9! is a safe limit for this problem)
        final int upperLimit = 7 * factorials.get(9);

        // Iterate through all numbers and check the condition
        for (int num = 10; num <= upperLimit; num++) {
            int sum = 0;
            int temp = num;

            // Calculate the sum of factorials of digits
            while (temp > 0) {
                int digit = temp % 10;
                sum += factorials.get(digit);
                temp /= 10;
            }

            // Check if the number equals the sum of the factorials of its digits
            if (sum == num) {
                System.out.println(num + " is a digit factorial number.");
            }
        }
    }

    public static void main(String[] args) {
        findDigitFactorialNumbers();
    }
}



/*
run:

145 is a digit factorial number.
40585 is a digit factorial number.


*/

 



answered 3 days ago by avibootz
...