Javascript Class to Generate Expanded Binomial Coefficients for a Power (AKA, a row in Pascals Triangle) December, 2007
The following JavaScript class enables you to get the expanded coefficients of a binomial raised to a particular power. Pass in the power and it will return an array of coefficients. For example, passing in a power of 6 returns {1, 6, 15, 20, 15, 6, 1}. This is also a row in Pascal's Triangle. It's using the following formula to calculate the coefficients, where n is the the power the binomial is raised to and k is the term position (0 to n).
Here is the class (PascalsTriangle.js):
function PascalsTriangle()
{
this.GetExpandedBinomialCoefficients = function(power)
{
var coefficients = new Array(power);
for (var index = 0; index <= power; index++)
{
coefficients[index] = this.GetExpandedBinomialCoefficient(power, index);
}
return coefficients;
}
this.GetExpandedBinomialCoefficient = function(power, term)
{
return this.GetFactorial(power) / (this.GetFactorial(term) * this.GetFactorial(power - term));
}
this.GetFactorial = function(value)
{
if (value <= 1)
return 1;
else
return value * this.GetFactorial(value - 1);
}
}
The class can be used as follows:
var pascalsTriangle = new PascalsTriangle();
var coefficients = pascalsTriangle.GetExpandedBinomialCoefficients(6);
alert(coefficients.join(' '));
This video covers Pascal's Triangle...