Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,907 questions

51,839 answers

573 users

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

1 Answer

0 votes
#include <stdio.h>

#define MAX_DIGIT 9

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

// Function to compute the factorial of a number
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
void findDigitFactorialNumbers() {
    int factorials[MAX_DIGIT + 1];
    
    // Precompute factorials of digits 0-9
    for (int i = 0; i <= MAX_DIGIT; i++) {
        factorials[i] = factorial(i);
    }

    // Define an upper limit (7 * 9! is a safe limit)
    int upperLimit = 7 * factorials[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[digit];
            temp /= 10;
        }

        // Check if the number equals the sum of the factorials of its digits
        if (sum == num) {
            printf("%d is a digit factorial number.\n", num);
        }
    }
}

int main() {
    findDigitFactorialNumbers();
}



/*
run:

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

*/



 



answered Nov 9, 2025 by avibootz
edited Nov 9, 2025 by avibootz
...