note 57895 added to ref.math
| From: | monte at ohrt dot com | Date: | Tue, 18 Oct 2005 13:37:30 +0000 |
| Subject: | note 57895 added to ref.math | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-97169@lists.php.net to get a copy of this message | ||
This is an efficient method of calculating the binomial coefficient C(n,k). This code was derived
from Owant: Mastering Algorithms with Perl.
<?php
// calculate binomial coefficient
function binomial_coeff($n, $k) {
$j = $res = 1;
if($k < 0 || $k > $n)
return 0;
if(($n - $k) < $k)
$k = $n - $k;
while($j <= $k) {
$res *= $n--;
$res /= $j++;
}
return $res;
}
?>
If you compiled php with --enable-bcmath, you can get full integer values of extremely large numbers
by replacing:
$res *= $n--;
$res /= $j++;
with:
$res = bcmul($res, $n--);
$res = bcdiv($res, $j++);
----
Manual Page -- http://www.php.net/manual/en/ref.math.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+57895
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+57895&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+57895&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+57895&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+57895&report=yes&reason=useless
Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+57895&report=yes&reason=non-english
Delete: already in docs -- http://master.php.net/manage/user-notes.php?action=delete+57895&report=yes&reason=already+in+docs
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+57895&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+57895&report=yes
Search -- http://master.php.net/manage/user-notes.php