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

Comments

2 responses to “PHP Factorial and Combination functions”

  1. Peter Reginald Avatar
    Peter Reginald

    Thank you. Very short and sweet.

  2. Alastair Avatar
    Alastair

    Super little snippet!

Leave a Reply

Your email address will not be published. Required fields are marked *