-1

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);
}
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
  • This seems like a very good time to learn how to [*debug*](how to debug small programs | Fabulous adventures in coding) your programs. Like for example using a [*debugger*](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) to step through your code line by line while monitoring variables and their values. That should make it easy to see when things go wrong. – Some programmer dude Apr 20 '23 at 06:19
  • This handy little tool: https://godbolt.org/z/YxPYeEzb6 should give a pretty solid hint at what went wrong. A debugger will help you better understand it and lead you to a solution. – user4581301 Apr 20 '23 at 06:21
  • Side note: check the diagnostic output. Your program may be exiting with an error code that tells you pretty much exactly what happened if you look the error code up. – user4581301 Apr 20 '23 at 06:23
  • There is a minor problem that an `int` is not guaranteed to be able to represent factorials of `8` or `9` (and there are real-world implementations - which support a 16-bit `int` - which cannot). To have such a guarantee, use `long` instead. – Peter Apr 20 '23 at 07:09
  • My rule: *the maximum recursion depth for a recursive function shall be **O(log n)***. Having a **O(n)** depth like this implementation is asking for trouble: it will quickly crash with (not so) big `n`. And this type of recursive function can be very easily converted to a loop, that is easier to understand, easier to debug, safer and faster. – prapin Apr 20 '23 at 18:17

1 Answers1

1

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.