Created
April 15, 2013 23:31
-
-
Save jeetsukumaran/5392166 to your computer and use it in GitHub Desktop.
Calculating the binomial coefficient in C++.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Calculates the binomial coefficient, $\choose{n, k}$, i.e., the number of | |
* distinct sets of $k$ elements that can be sampled with replacement from a | |
* population of $n$ elements. | |
* | |
* @tparam T | |
* Numeric type. Defaults to unsigned long. | |
* @param n | |
* Population size. | |
* @param k | |
* Number of elements to sample without replacement. | |
* | |
* @return | |
* The binomial coefficient, $\choose{n, k}$. | |
* | |
* @note | |
* Modified from: http://etceterology.com/fast-binomial-coefficients | |
*/ | |
template <class T = unsigned long> | |
T binomial_coefficient(unsigned long n, unsigned long k) { | |
unsigned long i; | |
T b; | |
if (0 == k || n == k) { | |
return 1; | |
} | |
if (k > n) { | |
return 0; | |
} | |
if (k > (n - k)) { | |
k = n - k; | |
} | |
if (1 == k) { | |
return n; | |
} | |
b = 1; | |
for (i = 1; i <= k; ++i) { | |
b *= (n - (k - i)); | |
if (b < 0) return -1; /* Overflow */ | |
b /= i; | |
} | |
return b; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for sharing this code, but the is a error with the default template argument and the overflow return code. -1 can not be returned as an unsigned value.