C++: Evaluate Binomial Coefficients

Bjarne-stroustrup
 

This programming task, is to calculate ANY binomial coefficient.

However, it has to be able to output \binom{5}{3}, which is 10.

This formula is recommended:

\binom{n}{k} = \frac{n!}{(n-k)!k!} = \frac{n(n-1)(n-2)\ldots(n-k+1)}{k(k-1)(k-2)\ldots 1}

double Factorial(double nValue)
{
	double result = nValue;
	double result_next;
	double pc = nValue;
	do
	{
		result_next = result*(pc-1);
		result = result_next;
		pc--;
	}while(pc>2);
	nValue = result;
	return nValue;
}

double EvaluateBinomialCoefficient(double nValue, double nValue2)
{
	double result;
	if(nValue2 == 1)return nValue;
	result = (Factorial(nValue))/(Factorial(nValue2)*Factorial((nValue - nValue2)));
	nValue2 = result;
	return nValue2;
}

Implementation:

int main()
{
	cout<<"The Binomial Coefficient of 5, and 3, is equal to: "<< EvaluateBinomialCoefficient(5,3);
	cin.get();
}
Output:
The Binomial Coefficient of 5, and 3, is equal to: 10

SOURCE

Content is available under GNU Free Documentation License 1.2.