简体   繁体   中英

Memoized ncr recursive factorial problem not working for large inputs

I'm trying to calculate nck combinations problem using recursion and memoization. It is working well for small inputs. However, it is failing for large inputs.

ans = n! / ( (nk)! * k! )

For 8C3, answer is 56. [working]

For 156C12, expected output is 281014969393251275 [not working]

How do I scale or optimize this?

Click here to run the code: http://cpp.sh/9ijiy

#include <iostream>
#include <map>
using namespace std;

long long int calls=0; // I know global vars are bad, but, i'm only using it for checking number of recursive calls

long long int fact(int n)
{
    calls++;
    static map<int, long long int> cache = {{0,1},{1,1}}; // factorial of 0 and 1 is 1

    if(cache.find(n) == cache.end()) // if n is NOT found
    {
        long long int ans = (long long int)n*fact(n-1);
        cache.insert(pair<int, long long int>(n,ans));
    }

    return cache[n];

}
long long int combin(int n, int k)
{
    return fact(n)/(fact(n-k)*fact(k));
}
int main()
{
    calls=0; cout << "8C3 is " << combin(8,6) << endl;
    cout << "Number of calls is " << calls << endl;

    calls=0; cout << "156C12 is " << combin(156,12) << endl;
    cout << "Number of calls is " << calls << endl;

    return 0;
}

Well, since you're having 156! along the way, which is 276 digits long (according to google) it's not going to fit in any of the default c++ data type for sure. The only solution I can think of is implementing some other, extending way of storing and operating on really big numbers. The first that comes to mind is implementing column multiplication (that thing from elementary school) and using strings (instead of long long) to store intermediate values in your cache. It's not gonna be efficient (of particularly pleasant to code), but since strings can hold infinitely (not really, but good enough) long sequence of characters it's possible to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM