Search code examples
c++sumfactorialdigits

sum of factorials of digits


I want to find 3digit number that the sum of the factorials of it's digits is the same as that number.

What is the problem in my codes since nothing shows.

Test function gives each digit and fact function compute the factorial.

#include <iostream>
using namespace std;

int fact(int y);
int test(int x);

int main()
{

    for (size_t i = 100; i < 1000; i++)
    {
        int sum = 0;
        int x = i;
        while (x > 0)
        {
            sum += test(x);
            x /= 10;
        }

        if (sum == i)
        {
            cout << i << endl;
        }
        
    }

    return 0;
}
int fact(int y)
{
    if (y == 1)
    {
        return 1;
    }
    else
        return y * fact(y - 1);
}
int test(int x)
{
    int r;

    r = x % 10;
    return fact(r);
}

Solution

  • Your int fact(int y) function is wrong. You forgot the case y = 0.

    int fact(int y) {
        if (y <= 1) {
            return 1;
        }
        else return y * fact(y - 1);
    }
    

    In addition, you need to calculate the factorial of digits so that you can cache it.