Skip to content

Instantly share code, notes, and snippets.

@lesterchan
Created April 3, 2014 15:20
Show Gist options
  • Save lesterchan/9956420 to your computer and use it in GitHub Desktop.
Save lesterchan/9956420 to your computer and use it in GitHub Desktop.
In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. There are 2 ways to archive it, by iterative function or by recursive function.
<?php
function factorial_iterative($n)
{
$k = 1;
for($i = $n; $i > 1; $i--)
{
$k *= $i;
}
return $k;
}
function factorial_recursive($n)
{
if($n < 2)
{
return 1;
}
else
{
return ($n * factorial_recursive($n - 1));
}
}
echo factorial_iterative(5)."\n";
echo factorial_iterative(10)."\n";
echo factorial_iterative(15)."\n";
echo "\n";
echo factorial_recursive(5)."\n";
echo factorial_recursive(10)."\n";
echo factorial_recursive(15)."\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment