Skip to content

Instantly share code, notes, and snippets.

@ferreiro
Created August 29, 2015 11:32
Show Gist options
  • Save ferreiro/84148bb8c7a4a7c0af7b to your computer and use it in GitHub Desktop.
Save ferreiro/84148bb8c7a4a7c0af7b to your computer and use it in GitHub Desktop.
Binomial coefficient in javascript
// Binomial coefficient
// Credits: github.com/jgferreiro
examples();
function examples() {
var a, b; // numerator and denominator of our coeffiecient
a = 2; b = 1;
console.log('Binomial for a = ' + a + " and b = "+ b + ' is ' + binomialCoefficient(a, b));
a = 18; b = 2;
console.log('Binomial for a = ' + a + " and b = "+ b + ' is ' + binomialCoefficient(a, b));
}
// Returns the binomial coefficient
// where a is the total set of posibbilites
// and b is the number of combinatios we're interested in
function binomialCoefficient(a, b) {
numerator = fact(a);
denominator = fact(a-b) * fact(b);
return numerator / denominator;
}
// Factorial function.
function fact(x) {
if(x==0) return 1;
return x * fact(x-1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment