Strong number problem in C++ but something is wrong with my code

Advertisements

I’m coding for the Strong number problem and when I run it, i passed 3 cases. But when I run 4th case nothing happens.

I passed: 1, 2, 145 but 40585.

Here is my code:

#include <iostream>

using namespace std;

int Get(int n);
int Factorial(int n, int sum);

int main()
{
    system("cls");

    int n;

    cout << "Enter. \n";
    cin >> n;
    if (n == Get(n))
    {
        cout << "True. \n";
    }
    else
    {
        cout << "False. \n";
    }

    return 0;
}

int Get(int n)
{
    static int sum = 0;
    if (n / 10) 
    {
        Get (n / 10);
    }
    return sum += Factorial(n % 10, 1);
}

int Factorial(int n, int sum)
{
    if (n == 1)
    {
        return sum;
    }
    else
    {
        return Factorial(n - 1, sum *= n);
    }
}

I don’t know why, so pls help me !

>Solution :

The problem is that in this line:

return sum += Factorial(n % 10, 1);

You call Factorial with n % 10 which can be 0.
This is not handled well by Factorial (it will recurse infinitely with negative values for n).

You can fix it by changing the recursion stop condition in Factorial to:

if (n <= 1)
{ 
   // ... 
}

A side note:

If you can implement a function using iteration (i.e. loops) instead of recursion – this is usually recommneded. This is because recursion uses the stack which is usually relatively small.
For calculating factorial you have to cope with an additional issue of int overflowing very fast – 13! is already too big to be stored in a 32 bit integer. You can handle it by e.g. using a 64 bit integer or some big number libarary for bigger values.
However – in this specific case since the Factorial is calculated for a max value of 9 both issues are OK.

As @lastchance commented, you can also keep all the required 10 values (for 0! .. 9!) in a precalculated array.

Leave a Reply Cancel reply