Posted By

Scooter on 06/14/08


Tagged

math


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

koncept
IsraelTorres
nazir


Factorial


 / Published in: PHP
 

URL: http://reusablecode.blogspot.com/2008/06/factorial.html

  1. <?php
  2. /*
  3.   PHP Mathematics Library - Factorial
  4.  
  5.   Copyright (c) 2008, reusablecode.blogspot.com; some rights reserved.
  6.  
  7.   This work is licensed under the Creative Commons Attribution License. To view
  8.   a copy of this license, visit http://creativecommons.org/licenses/by/3.0/ or
  9.   send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford, California
  10.   94305, USA.
  11.   */
  12.  
  13. // Determine the factorial for a given number
  14. function factorial($x)
  15. {
  16. $result = 1;
  17.  
  18. if ($x > 1)
  19. {
  20. for ($i = 2; $i <= $x; $i++)
  21. {
  22. $result *= $i;
  23. }
  24. }
  25.  
  26. return $result;
  27. }
  28.  
  29. // Returns the number of combinations, without regard to order, of y items that can be made from a pool of x items.
  30. // Requires factorial()
  31. function combinatorial($x, $y)
  32. {
  33. return (($x >= $y) && ($y > 0)) ? factorial($x) / factorial($y) / factorial($x - $y) : 0;
  34. }
  35.  
  36. // Returns the number of permutations, with regard to order, of y items that can be made from a pool of x items.
  37. // Requires factorial()
  38. function permutations($x, $y)
  39. {
  40. return factorial($x) / factorial($x - $y);
  41. }
  42. ?>

Report this snippet  

You need to login to post a comment.