Created
April 3, 2014 15:20
-
-
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.
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 | |
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