Skip to content

Instantly share code, notes, and snippets.

@jeetsukumaran
Created April 15, 2013 23:31
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jeetsukumaran/5392166 to your computer and use it in GitHub Desktop.
Save jeetsukumaran/5392166 to your computer and use it in GitHub Desktop.
Calculating the binomial coefficient in C++.
/**
* 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;
}
@burner
Copy link

burner commented Dec 17, 2014

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment