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

1 Answer

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

// Function to compute the factorial of a number
fn factorial(n: u32) -> u32 {
    let mut fact = 1;

    for i in 2..=n {
        fact *= i;
    }

    fact
}

// Function to find all numbers equal to the sum of the factorials of their digits
fn find_digit_factorial_numbers() {
    // Precompute factorials of digits 0-9
    let factorials: Vec<u32> = (0..=9).map(factorial).collect();

    // Define an upper limit (7 * 9! is a safe limit for this problem)
    let upper_limit = 7 * factorials[9];

    // Iterate through all numbers and check the condition
    for num in 10..=upper_limit {
        let mut sum = 0;
        let mut temp = num;

        // Calculate the sum of factorials of digits
        while temp > 0 {
            let digit = temp % 10;
            sum += factorials[digit as usize];
            temp /= 10;
        }

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

fn main() {
    find_digit_factorial_numbers();
}



/*
run:

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

*/

 



answered 2 days ago by avibootz
edited 2 days ago by avibootz
...