Skip to content

Commit 1239f20

Browse files
committed
Added simple explanation of recursion
1 parent 6700401 commit 1239f20

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

chap-05/recursion-explained.php

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
<?php
2+
/**
3+
* Created by PhpStorm.
4+
* User: bert
5+
* Date: 4/10/18
6+
* Time: 14:14
7+
*/
8+
9+
/**
10+
* Recursion is a way to solve larger problems by dividing them into smaller problems. Recursive functions MUST call
11+
* themselves to break down the problems. For example :
12+
*
13+
* Mathematical factorials :
14+
*
15+
* 5! = 5 * 4 * 3 * 2 * 1
16+
* 4! = 4 * 3 * 2 * 1
17+
* 3! = 3 * 2 * 1
18+
* 2! = 2 * 1
19+
* 1! = 1
20+
*
21+
* The above can be rewritten :
22+
*
23+
* 5! = 5 * 4!
24+
* 4! = 4 * 3!
25+
* 3! = 3 * 2!
26+
* 2! = 2 * 1!
27+
* 1! = 5 * 0!
28+
* 0! = 1
29+
*
30+
* Mathematically this boils down do :
31+
*
32+
* n! = n * (n-1)!
33+
*
34+
* Functionally it goes like this for 3! = 3 * 2! :
35+
*
36+
* Step 1 : 3! = 3 * 2!
37+
* Step 2 : 2! = 2 * 1!
38+
* Step 3 : 1! = 1 * 0!
39+
* Step 4 : 0! = 1 <== This is the actual end of recursion, where we start to get results in.
40+
* Step 5 : 1! = 1 * 1 = 1
41+
* Step 6 : 2! = 2 * 1 = 2
42+
* Step 7 : 3! = 3 * 2 = 6
43+
*
44+
* Recursive functions have these three properties which should be met :
45+
*
46+
* 1) Should be called on a smaller subproblem of the larger problem
47+
* 2) Should have a base case which ends the recursion.
48+
* 3) Should not be any cycle : should not make a recursive call to the same problem (endless loop)
49+
*
50+
*/
51+
52+
53+
$n = 10;
54+
55+
echo "The factor of {$n} is : " .factorial($n) . PHP_EOL;
56+
57+
echo "Be sure to check the docblock of this file for more explanation!" . PHP_EOL;
58+
59+
function factorial(int $n) : int
60+
{
61+
62+
// This is the base case which ends recursion.
63+
if ($n == 0){
64+
return 1;
65+
}
66+
67+
// This is the recursive call. Notice how we lower n to eventually reach the base case.
68+
return $n * factorial($n - 1);
69+
}
70+

0 commit comments

Comments
 (0)