©
Dokumen ini menggunakan Manual laman web PHP Cina Lepaskan
Example #1 Factorial function using GMP
<?php
function fact ( $x )
{
$return = 1 ;
for ( $i = 2 ; $i <= $x ; $i ++) {
$return = gmp_mul ( $return , $i );
}
return $return ;
}
echo gmp_strval ( fact ( 1000 )) . "\n" ;
?>
This will calculate factorial of 1000 (pretty big number) very fast.
[#1] Ganzert [2015-10-16 04:58:19]
in the example above, this following line:
for ($i=2; $i < $x; $i++) {
should be replaced by:
for ($i=2; $i <=$x; $i++) {
Cheers
Ganzert
[#2] Juliano Barreto [2015-09-15 17:59:42]
I forgot to mention. You need (obviously) to remove the gmp function for a usual one. Like this:
function fact($num)
{
$res = 1;
for ($n = $num; $n >= 1; $n--)
$res = $res*$n;
return $res;
}
[#3] Juliano Barreto [2015-09-15 17:38:25]
This function isn't pointless if you don't have the GMP library installed.
[#4] Jonathon [2014-02-06 03:21:54]
Of course, this example is pointless because there is gmp_fact().