Simpatico  v1.10
Binomial.cpp
1 /*
2 * Util Package - C++ Utilities for Scientific Computation
3 *
4 * Copyright 2010 - 2017, The Regents of the University of Minnesota
5 * Distributed under the terms of the GNU General Public License.
6 */
7 
8 #include "Binomial.h"
9 #include <util/global.h>
10 
11 namespace Util
12 {
13 
14  int Binomial::maxN_ = -1;
15  GArray<int> Binomial::coeffs_;
16 
17  void Binomial::setup(int maxN)
18  {
19  UTIL_CHECK(maxN >= 0);
20  if (maxN <= maxN_) return;
21  maxN_ = maxN;
22 
23  // Create coeff array of correct size , all zero elements
24  int size = (maxN + 1)*(maxN +2)/2;
25  coeffs_.resize(size);
26  for (int i = 0; i < size; ++i) {
27  coeffs_[i] = 0;
28  }
29 
30  // Generate Pascal's triangle to set coefficients
31  coeffs_[0] = 1;
32  if (maxN == 0) return;
33  int n, m, bc, bp;
34  for (n = 1; n <= maxN; ++n) {
35  bc = n*(n+1)/2;
36  coeffs_[bc] = 1;
37  if (n > 1) {
38  bp = (n-1)*n/2;
39  for (m = 1; m < n; ++m) {
40  coeffs_[bc + m] = coeffs_[bp + m - 1] + coeffs_[bp + m];
41  }
42  }
43  coeffs_[bc + n] = 1;
44  }
45  }
46 
47  int Binomial::coeff(int n, int m)
48  {
49  UTIL_CHECK(n >= 0);
50  UTIL_CHECK(m >= 0 && m <= m);
51  if (n > maxN_) setup(n);
52  return coeffs_[(n*(n+1)/2) + m] ;
53  }
54 
55 }
static int coeff(int n, int m)
Return coefficient "n choose m", or C(n, m) = n!/(m!(n-m)!).
Definition: Binomial.cpp:47
File containing preprocessor macros for error handling.
static void setup(int nMax)
Precompute all combinations C(n, m) up to n = nMax.
Definition: Binomial.cpp:17
Utility classes for scientific computation.
Definition: accumulators.mod:1
#define UTIL_CHECK(condition)
Assertion macro suitable for serial or parallel production code.
Definition: global.h:68
void resize(int n)
Resizes array so that it contains n elements.
Definition: GArray.h:339