PSCF v1.1
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
11namespace 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
48 {
49 if (coeffs_.capacity() > 0) {
50 coeffs_.deallocate();
51 }
52 maxN_ = -1;
53 }
54
55 int Binomial::coeff(int n, int m)
56 {
57 UTIL_CHECK(n >= 0);
58 UTIL_CHECK(m >= 0 && m <= m);
59 if (n > maxN_) setup(n);
60 return coeffs_[(n*(n+1)/2) + m] ;
61 }
62
63}
static void setup(int nMax)
Precompute all combinations C(n, m) up to n = nMax.
Definition: Binomial.cpp:17
static int coeff(int n, int m)
Return coefficient "n choose m", or C(n, m) = n!/(m!(n-m)!).
Definition: Binomial.cpp:55
static void clear()
Release all static memory.
Definition: Binomial.cpp:47
void resize(int n)
Resizes array so that it contains n elements.
Definition: GArray.h:339
void deallocate()
Deallocate (delete) underlying array of pointers.
Definition: GArray.h:286
int capacity() const
Return physical capacity of array.
Definition: GArray.h:448
File containing preprocessor macros for error handling.
#define UTIL_CHECK(condition)
Assertion macro suitable for serial or parallel production code.
Definition: global.h:68
Utility classes for scientific computation.
Definition: accumulators.mod:1