Last active
December 7, 2018 15:46
-
-
Save azjezz/d4a468396dccea3b594836778908a5e2 to your computer and use it in GitHub Desktop.
PHP Factorial without using a loop
This file contains hidden or 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); | |
/** | |
* Calculate factorial using recursive function call | |
* | |
* @see https://3v4l.org/oeZp9 | |
* | |
* @param int $n | |
* | |
* @throws InvalidArguemntException | |
* @return int $factorial | |
*/ | |
function factorial(int $n): int { | |
if ($n < 0) { | |
throw new InvalidArgumentException('The factorial function is defined for non-negative integers only.'); | |
} | |
if ($n === 0 || $n === 1) { | |
return 1; | |
} | |
return $n * factorial($n-1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment