因子计算器返回INF值作为结果

时间:2014-08-11 11:11:01

标签: php

以下函数返回结果INF。所以我想这是因为数字太大但我该如何解决呢?

class Factoriel {

public function calculate() {
    if(func_num_args() != 1)
        throw new Exception ("Invalid arguments count for method calculate!");

    if(($n = (int)func_get_arg(0)) <= 0)
        throw new Exception ("Invalid argument supplied for method calculate!");

    $result = 1;
    foreach(range(1, $n) as $current)
        $result = $this->multiply ($result, $current);

    return $result;
}
private function multiply($left, $right) {
    return $left * $right;
   }
}

$factoriel = new Factoriel();

echo $factoriel->calculate(1500);

2 个答案:

答案 0 :(得分:2)

1500的因子对于PHP来说太大了,这就是为什么你得到INF,意思是无限数。请阅读http://php.net/manual/en/function.is-infinite.php

答案 1 :(得分:2)

您可以使用bcmul函数进行乘法,例如

return bcmul("$left","$right");

而不是

return $left * $right;

DEMO of fact(500);