Created
May 3, 2017 01:39
-
-
Save rmamont/cee1424773432bebc5d9f52d09b5e2a6 to your computer and use it in GitHub Desktop.
Factorial in recursive and iterative methods
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 | |
| function factorial_recursive($num) | |
| { | |
| if ($num < 0) { | |
| return 'Param must be larger than zero!!'; | |
| } | |
| if ($num < 2) { | |
| return $num; | |
| } | |
| return factorial_recursive($num - 1) * $num; | |
| } | |
| assert('Param must be larger than zero!!' == factorial_recursive(-5)); | |
| assert(0 == factorial_recursive(0)); | |
| assert(1 == factorial_recursive(1)); | |
| assert(120 == factorial_recursive(5)); | |
| assert(24 == factorial_recursive(4)); | |
| function factorial_iterative($num) | |
| { | |
| $iter = function($num, $acc) use (&$iter) { | |
| if ($num < 0) { | |
| return 'Param must be larger than zero!!'; | |
| } | |
| if ($num == 0) { | |
| return 0; | |
| } | |
| if ($num == 1) { | |
| return $acc; | |
| } | |
| return $iter($num - 1, $acc * $num); | |
| }; | |
| return $iter($num, 1); | |
| } | |
| assert('Param must be larger than zero!!' == factorial_iterative(-5)); | |
| assert(0 == factorial_iterative(0)); | |
| assert(1 == factorial_iterative(1)); | |
| assert(120 == factorial_iterative(5)); | |
| assert(24 == factorial_iterative(4)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment