Skip to content

Instantly share code, notes, and snippets.

@azjezz
Last active December 7, 2018 15:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save azjezz/d4a468396dccea3b594836778908a5e2 to your computer and use it in GitHub Desktop.
Save azjezz/d4a468396dccea3b594836778908a5e2 to your computer and use it in GitHub Desktop.
PHP Factorial without using a loop
<?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