clean-code-php icon indicating copy to clipboard operation
clean-code-php copied to clipboard

Problem in the fibonacci function

Open mstolt opened this issue 2 years ago • 0 comments

There is a problem in the fibonacci function. The fibonacci number is not defined for numbers < 0. The current function would run in an endless loop (as far as PHP stack count reaches).

function fibonacci(int $n): int
{
    if ($n < 0){
       throw new Exception('Only positive integer are valid arguments'); 
   }

    if ($n === 0 || $n === 1) {
        return $n;
    }

    if ($n >= 50) {
        throw new Exception('Not supported');
    }

    return fibonacci($n - 1) + fibonacci($n - 2);
}

Kind regards and thanks for the inspiring clean-code-php examples.

mstolt avatar Feb 13 '23 13:02 mstolt