Created
August 29, 2015 11:32
-
-
Save ferreiro/84148bb8c7a4a7c0af7b to your computer and use it in GitHub Desktop.
Binomial coefficient in javascript
This file contains 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
// 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