编写程序来计算nCr值(C ++)

时间:2014-10-31 19:30:10

标签: c++ binomial-coefficients

我写了下面的代码来计算n个testCount值的nCr。它似乎对我的价值观很好,但黑客地球的测试用例失败了,问题链接http://www.hackerearth.com/problem/golf/minimal-combinatorial/description/ 任何人都可以告诉我逻辑中潜在的谬误

`#include <iostream>
 using namespace std;

 int main()
{
    int testCount; 
    int n , r;
    cin >> testCount;
    for (int i = 0 ; i < testCount ; i++)
    {

        long int a=1;
        long int b=1;
        long int c=1;
        cin >> n;
        cin >> r;
        for (int i = n ; i > 1 ; i--)
        {
             a = a * i;
        }
        for (int i = n-r; i >= 1 ; i--)
        {
            b=b*i;
        }
       for (int i=r;i >=1;i--)
       {
           c=c*i;
       }
       long int result=a/(b*c);
       cout << result<<"\n";
    }

    return 0;
}

` 简化的分子和分母情况

 `#include <iostream>
  using namespace std;

int main()
{
   int testCount; 
   int n , r;
   cin >> testCount;
  for (int i = 0 ; i < testCount ; i++)
  {

       long int numerator=1;
       long int denominator=1;
       cin >> n;
       cin >> r;
       for (int i = n ; i > r ; i--)
       {
          numerator = numerator * i;
       }
       for (int i = n-r; i >= 1 ; i--)
       {
           denominator=denominator*i;
       } 

       long int result=numerator/denominator;
       cout << result;
   }

    return 0;

} `

1 个答案:

答案 0 :(得分:2)

两个代码都可能溢出(即使结果应该适合64位整数)

您可以尝试:

std::uint64_t cnr(int n, int r)
{
    std::uint64_t ans = 1;
    r = std::min(r, n - r);

    for(int j = 1; j <= r; j++, n--) {
        // all following do: ans = (ans * n) / j;
        // but the 2 first cases do some simplifications
        // to reduce the possibility of overflow

        if (n % j == 0) {
            ans *= n / j; 
        } else if (ans % j == 0) {
            ans = (ans / j) * n;
        } else {
            ans = (ans * n) / j;
        }
    }
    return ans;
}