Saturday, June 14, 2008

Factorial

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

  1. function factorial(x)
  2.     dim result
  3.     result = 1
  4.     if x > 1 then
  5.         for i = 2 to x
  6.             result = result * i
  7.         next
  8.     end if
  9.     factorial = result
  10. end function

PHP

  1. function factorial($x)
  2. {
  3.     $result = 1;
  4.     if ($x > 1)
  5.     {
  6.         for ($i = 2; $i <= $x; $i++)
  7.         {
  8.             $result *= $i;
  9.         }
  10.     }
  11.     return $result;
  12. }

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

  1. function combinatorial(x, y)
  2.     if (x >= y) and (y > 0) then
  3.         combinatorial = factorial(x) / factorial(y) / factorial(x - y)
  4.     else
  5.         combinatorial = 0
  6.     end if
  7. end function

PHP

  1. function combinatorial($x, $y)
  2. {
  3.     return (($x >= $y) && ($y > 0)) ? factorial($x) / factorial($y) / factorial($x - $y) : 0;
  4. }

We can also get the number of permutations of y items that can be made from a pool of x items.


ASP

  1. function permutations(x, y)
  2.     permutations = factorial(x) / factorial(x - y)
  3. end function

PHP

  1. function permutations($x, $y)
  2. {
  3.     return factorial($x) / factorial($x - $y);
  4. }

No comments: