Algorithm 如何计算大数的组合

Algorithm 如何计算大数的组合,algorithm,math,combinations,Algorithm,Math,Combinations,我将数字排列计算为:- nPr=n/(右) 其中n和r是给定的。 1考虑使用BigInteger类型的类来表示您的大数字。BigInteger在Java和C#(4+版的.NET Framework)中可用。从你的问题看来,你好像在使用C++(你应该总是添加为标签)。因此,尝试查找并使用一个可用的C++ BigType类。 我所见过的计算二项式系数的最佳方法之一是。与其他一些方法相比,使用较大的N和K值溢出的可能性要小得多 static long GetBinCoeff(long N, long

我将数字排列计算为:-

nPr=n/(右)

其中n和r是给定的。
1考虑使用BigInteger类型的类来表示您的大数字。BigInteger在Java和C#(4+版的.NET Framework)中可用。从你的问题看来,你好像在使用C++(你应该总是添加为标签)。因此,尝试查找并使用一个可用的C++ BigType类。

我所见过的计算二项式系数的最佳方法之一是。与其他一些方法相比,使用较大的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;
}
静态长GetBinCoeff(长N,长K)
{
//此函数获取基于N和K的唯一组合的总数。
//N是项目总数。
//K是组的大小。
//唯一组合的总数=N!/(K!(N-K)!)。
//此函数的效率较低,但在N和K较大时更可能不会溢出。
//摘自:http://blog.plover.com/math/choose.html
//
如果(K>N)返回0;
长r=1;
长d;

对于(d=1;d)请查看关于组合的wikipedia页面,解决方案就在那里。备注:对于n=100,r=50,您的nCr=1008913445564193334812497256,它不适合64位变量。请参阅。另外,请记住nCr=nC(n-r).回答得很好.这在C#NET 4.5.2上能改进吗?我不知道如何改进.你有改进的建议吗?
#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;
}
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;
}