Basic Image AlgorithmS Library  2.8.0
 All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator Friends Groups Pages
TestBinomialCoefficient.cpp
1 #include <Base/Math/BinomialCoefficient.hh>
2 
3 #include <Base/Math/Random.hh>
4 #include <Base/Debug/Exception.hh>
5 
6 #include <iostream>
7 
8 using namespace BIAS;
9 using namespace std;
10 
11 unsigned binomial_coeff(const unsigned n, const unsigned k);
12 
13 
14 int main(int argc, char *argv[])
15 {
16  const unsigned num = 1000;
17  const unsigned max_n = 25;
18  string arg1;
19  if (argc==2) arg1 = argv[1];
20  const bool verbose = (arg1!="silent");
21 
22  Random MyRandom;
23 
24  for (unsigned t=0; t<num; t++){
25  const unsigned n = MyRandom.GetUniformDistributedInt(0u, max_n);
26  const unsigned k = MyRandom.GetUniformDistributedInt(0u, n);
27  try {
28  #if __GNUC_PREREQ(4,6)
29  #pragma GCC diagnostic ignored "-Wunused-but-set-variable"
30  #endif
31  long long unsigned bc = 0;
33  #if __GNUC_PREREQ(4,6)
34  #pragma GCC diagnostic ignored "-Wunused-but-set-variable"
35  #endif
36  unsigned bc_rec = 0;
37  bc_rec = binomial_coeff(n, k);
38  BIASASSERT(bc == bc_rec);
39  } catch (BaseException &ex) {
40  cout << "cannot compute "<<n<<" over "<<k<<": overflow:"<<ex.What()<<endl;
41  }
42  if (verbose && t%10==0 ){
43  cout << "."<<flush;
44  }
45 
46  }
47  if (verbose){
48  cout << endl;
49  }
50 }
51 
52 unsigned binomial_coeff(const unsigned n, const unsigned k)
53 {
54  if ((k==0) || (k==n) || (k==0 && n==0)){
55  return 1u;
56  }
57  assert(n>0 && k>0);
58  unsigned res1 = binomial_coeff(n-1, k-1);
59  unsigned res2 = binomial_coeff(n-1, k);
60  unsigned binomial_coefficent = res1 + res2;
61  if (binomial_coefficent < res1 ||
62  binomial_coefficent < res2){
63  BEXCEPTION("Overflow\n");
64  }
65  return binomial_coefficent;
66 }
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...
int GetUniformDistributedInt(const int min, const int max)
get uniform distributed random variable including min/max
Definition: Random.cpp:139
class for producing random numbers from different distributions
Definition: Random.hh:51
generic exception
Definition: Exception.hh:77
virtual const std::string & What() const
Definition: Exception.hh:95