function binomial_coefficient ($n, $k)
{
//variable and initializations
$the_result = 0;
$n_factorial = 0;
$k_factorial = 0;
$n_k_factorial = 0;
//calculate n,k n-k factorial
$n_factorial = factorial_integer($n);
$k_factorial = factorial_integer($k);
$n_k_factorial = factorial_integer($n - $k);
if ($n_factorial != "error" and
$k_factorial != "error" and
$n_k_factorial != "error")
{
$the_result = $n_factorial / ($k_factorial * $n_k_factorial);
}
else
{
return "error";
}
return $the_result;
}
function factorial_integer ($k)
{
//variable and initializations
$the_result = 1;
//check to see if k is an integer
if (!is_int($k))
{
return "error";
}
//check for k < 0
if ($k < 0)
{
return "error";
}
//0! = 1
if ($k == 0)
{
return 1;
}
//calculate the result
for ($i = 2; $i <= $k; $i++)
{
$the_result = $the_result * $i;
}
//return the value
return $the_result;
} |