Leo Jiang
Leo Jiang

Reputation: 26115

How can I do combinatorics in PHP?

I'm not too familiar with combinatorics, but I need to calculate C(m,n) using PHP. What's an easy way to do find C(m,n)?

Upvotes: 2

Views: 1282

Answers (2)

Josep Bonet Celorio
Josep Bonet Celorio

Reputation: 1

The factorial must return 1 in case the result is 0.

    function fact($n){
      $f=$n--;
      while($n>0)
        $f*=$n--;
      if($f==0){
        return 1;
      }
      return $f;
    }

Upvotes: 0

Leo Jiang
Leo Jiang

Reputation: 26115

I got it using formulas on Wikipedia. This should work:

function fact($n){
  $f=$n--;
  while($n>0)
    $f*=$n--;
  return $f;
}


function c($n,$m){
  return fact($n)/(fact($m)*fact($n-$m));
}

echo c(6,3);

Please let me know if there's something wrong with my function, thanks!

Upvotes: 2

Related Questions