Skip to content

Instantly share code, notes, and snippets.

@galvao
Created May 26, 2022 02:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save galvao/b28a96b490c7076f6a54cb986decd637 to your computer and use it in GitHub Desktop.
Save galvao/b28a96b490c7076f6a54cb986decd637 to your computer and use it in GitHub Desktop.
Finding the factorial of a number, recursively
<?php
declare(strict_types = 1);
/**
* factorialFactorial
* Finding the factorial of a $number by recursion
*
* @author Er Galvão Abbott <galvao@php.net>
*/
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