3

I have written the following code for finding n!. I am running this through CLI.

<?php 
    $handle = fopen("php://stdin", "r");
    $number = (int) trim(fgets($handle));
    $fact = calcFactorial($number);
    echo $fact . "\n";

function calcFactorial($number) {
    if ($number < 2) {
        return 1;
    } else {
        return $number * calcFactorial($number - 1);
    }
}
fclose($handle);
?>

The above code is working fine. But there are two issues with two different PHP installations.

  1. On one PC I get,

Fatal error: Maximum function nesting level of '100' reached, aborting!

To correct above problem I find the solution here. Is this the correct way to have a solution? Because it depends on a particular Default Value of 'xdebug.max_nesting_level' .

  1. On other PC I get,

INF

So what is the best approach to tackle this issue?

P.S.: I have gone through various solutions throughout this website but I am not able to conclude.

UPDATE: There is one function suggested. But can it be done without using any kind of function?

Community
  • 1
  • 1

1 Answers1

2

Nesting limit:

if the calcFactorial() can by non-recursive then you can change it to this:

function calcFactorial($number){

    if($number<2){
        return 1;
    }

    $ret = 1;
    for($i=2;$i<=$number;$i++){
        $ret = $ret*$i;
    }
    return $ret;
}

if has to be recursive you never be able to calc factorial of number bigger then Maximum function nesting level.

INF:

That means PHP thinks number is infinitive (to big to store in memory) ... i think (not sure) that answer is bigger than PHP_INT_MAX ...

You can confirm this by echo is_infinite($number);

you can try solve this with storing numbers as strings (of digits) or arrays (of digits) and than write some function to make multiplication of this strings (arrays) but it is not easy to do

Jakub Krajč
  • 46
  • 1
  • 7