PHP Factorial and Combination functions

A quick post on two functions for PHP that provide factorial and combination support.

function factorial($n) {
	if ($n <= 1) {
		return 1;
	} else {
		return factorial($n - 1) * $n;
	}
}

function combinations($n, $k) {
	//note this defualts to 0 if $n < $k
	if ($n < $k) {
		return 0;
	} else {
		return factorial($n)/(factorial($k)*factorial(($n - $k)));
	}
}

Posted

in

by

Tags: