【问题标题】:how to calculate combination of large numbers如何计算大数的组合
【发布时间】:2013-01-28 06:00:48
【问题描述】:

我将数字的排列计算为:-

nPr = n!/(n-r)!

其中给出了 n 和 r。 1<= n,r <= 100

i find p=(n-r)+1
and 
for(i=n;i>=p;i--)
  multiply digit by digit and store in array.

但是我将如何计算 nCr = n!/[r! * (n-r)!] 为相同的范围。?

我使用递归来做到这一点,如下所示:-

#include <stdio.h>
typedef unsigned long long i64;
i64 dp[100][100];
i64 nCr(int n, int r)
{
if(n==r) return dp[n][r] = 1;
if(r==0) return dp[n][r] = 1;
if(r==1) return dp[n][r] = (i64)n;
if(dp[n][r]) return dp[n][r];
return dp[n][r] = nCr(n-1,r) + nCr(n-1,r-1);
}

int main()
{
int n, r;
while(scanf("%d %d",&n,&r)==2)
{
    r = (r<n-r)? r : n-r;
    printf("%llu\n",nCr(n,r));
}
return 0;
}

但 n 60 。

【问题讨论】:

  • 查看wikipedia page on combination,解决方案就在那里。
  • 备注: 对于 n = 100,r = 50,你有 nCr = 100891344545564193334812497256,它不适合 64 位变量。
  • 另外,请记住 nCr = nC(n - r)。

标签: algorithm math combinations


【解决方案1】:

考虑使用 BigInteger 类型的类来表示您的大数字。 BigInteger 在 Java 和 C#(.NET Framework 4+ 版本)中可用。从您的问题来看,您似乎正在使用 C++(您应该始终将其添加为标签)。因此,请尝试在 herehere 中查找可用的 C++ BigInteger 类。

我见过的计算二项式系数的最佳方法之一是Mark Dominus。与其他一些方法相比,使用较大的 N 和 K 值溢出的可能性要小得多。

static long GetBinCoeff(long N, long K)
{
   // This function gets the total number of unique combinations based upon N and K.
   // N is the total number of items.
   // K is the size of the group.
   // Total number of unique combinations = N! / ( K! (N - K)! ).
   // This function is less efficient, but is more likely to not overflow when N and K are large.
   // Taken from:  http://blog.plover.com/math/choose.html
   //
   if (K > N) return 0;
   long r = 1;
   long d;
   for (d = 1; d <= K; d++)
   {
      r *= N--;
      r /= d;
   }
   return r;
}

只需将所有长定义替换为 BigInt 即可。

【讨论】:

  • 非常好的答案可以在 C# .NET 4.5.2 中改进吗?
  • 副手,我不明白怎么做。您有改进的建议吗?
猜你喜欢
  • 2017-02-08
  • 2014-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-26
  • 2013-01-17
  • 1970-01-01
相关资源
最近更新 更多