Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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. Thank u so much. Test function gives each digit and fact funtion 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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading