Created
May 26, 2022 02:34
-
-
Save galvao/b28a96b490c7076f6a54cb986decd637 to your computer and use it in GitHub Desktop.
Finding the factorial of a number, recursively
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types = 1); | |
/** | |
* factorialFactorial | |
* Finding the factorial of a $number by recursion | |
* | |
* @author Er Galvão Abbott <[email protected]> | |
*/ | |
function factorialFactorial(int $number, int $total = 0): int | |
{ | |
if ($number < 0) { | |
throw new Exception('Negative Factorials are undefined.'); | |
} | |
if ($number === 0) { | |
$total = 1; | |
} | |
if ($total === 0) { | |
$total = $number; | |
} | |
if ($number > 1) { | |
$total *= --$number; | |
$total = factorialfactorial($number, $total); | |
} | |
return $total; | |
} | |
// Example | |
try { | |
echo factorialfactorial(8) . PHP_EOL; | |
} catch (Exception $e) { | |
echo $e->getMessage() . PHP_EOL; | |
exit(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment