Basic Image AlgorithmS Library  2.8.0
 All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator Friends Groups Pages
BinomialCoefficient.cpp
1 #include <Base/Math/BinomialCoefficient.hh>
2 #include <Base/Debug/Exception.hh>
3 #include <Base/Debug/Error.hh>
4 
5 #include <limits>
6 #include <limits.h>
7 
8 using namespace BIAS;
9 using namespace std;
10 
11 long long unsigned BinomialCoefficient::
12 Compute(const unsigned n, const unsigned k)
13 {
14  if ((k==0) || (k==n) || (k==0 && n==0)){
15  return 1u;
16  }
17  if (2*k>n) {
18  return Compute(n, n-k);
19  }
20  long long unsigned prod = 1, old_prod;
21  BIASASSERT(n>=k);
22  const unsigned n_minus_k = n-k;
23  for (unsigned i=1; i<=n_minus_k; i++){
24  old_prod = prod;
25  prod *= (long long unsigned)(k+i);
26  if (prod<=old_prod){
27  BEXCEPTION("BinomialCoefficient::Compute("<<n<<", "<<k<<"): Overflow");
28  }
29  BIASASSERT(prod%i==0);
30  prod /= (long long unsigned)(i);
31  // changed if statement from if (prod>=numeric_limits<unsigned>::max())
32  if (prod>=UINT_MAX){
33  BEXCEPTION("BinomialCoefficient::Compute("<<n<<", "<<k<<"): Overflow");
34  }
35  }
36  return prod;
37 }
static long long unsigned Compute(const unsigned n, const unsigned k)
Computation of the binomial coefficient &quot;n over k&quot; The function throws an exception when overflow occ...