代码之家  ›  专栏  ›  技术社区  ›  Manjunath apardoe

记忆体ncr递归阶乘问题不适用于大输入

  •  0
  • Manjunath apardoe  · 技术社区  · 7 年前

    我在计算 nck公司 使用递归和记忆的组合问题。它在小投入下运行良好。然而,对于大投入来说,这是失败的。

    对于8C3,答案是56。[工作]

    [10115692输出无效]

    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;
    }
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   vrtex    7 年前

    好吧,既然你有156个!一直以来,它的长度是276位(根据google的数据),它肯定不适合任何默认的c++数据类型。我能想到的唯一解决方案是实现一些其他的扩展方法来存储和操作非常大的数字。首先想到的是实现列乘法(小学时的事),并使用字符串(而不是long long)在缓存中存储中间值。它不会很有效率(代码特别令人愉快),但是由于字符串可以无限地(不是真的,但足够好)保存很长的字符序列,所以这是可能的。

    推荐文章