This week we're going to delve into some discrete math, starting with factorial. The factorial of a number is the product of that number and all the numbers smaller than it. For example, the factorial of 3 is 1 x 2 x 3 = 6.
ASP
function factorial(x)dim resultresult = 1if x > 1 thenfor i = 2 to xresult = result * inextend iffactorial = resultend function
PHP
function factorial($x){$result = 1;if ($x > 1){for ($i = 2; $i <= $x; $i++){$result *= $i;}}return $result;}
Now that we have a function for factorial, we can also do combinatorial. Combinatorial tells us the number of combinations, without regard to order, of y items that can be made from a pool of x items.
ASP
function combinatorial(x, y)if (x >= y) and (y > 0) thencombinatorial = factorial(x) / factorial(y) / factorial(x - y)elsecombinatorial = 0end ifend function
PHP
function combinatorial($x, $y){return (($x >= $y) && ($y > 0)) ? factorial($x) / factorial($y) / factorial($x - $y) : 0;}
We can also get the number of permutations of y items that can be made from a pool of x items.
ASP
function permutations(x, y)permutations = factorial(x) / factorial(x - y)end function
PHP
function permutations($x, $y){return factorial($x) / factorial($x - $y);}
No comments:
Post a Comment