This is basically a way of taking complex problems and breaking them down to the simplest form.
In recursion we always have the base and recursive case;
The base case refers to the simplest instance of the problem; ie; sum([]) = 0, which means we can sum/add nothing, we down to our simplest form.
Now, what is a recursive case? think of this as a big problem that needs to be shrunk to the simplest form.
Using the sum example; sum 1([2,3,7]) and sum 2([2,3]) has sum([2,3]) as a repeating value, simplicity is king in the world of programming, with the aim of making progress to the base case.
Let us jump to examples, were we will tackle the factorial problem, the recursion problem and the Tower of Hanoi problem.
The Factorial Problem
Let’s write a function “fact” that takes in a number as an argument and returns the factorial of that number.
factorial works as follows; the factorial of ’n’ is the product of all positive numbers from 1 to ’n’ example:
factorial (7) = 5040 = 7*6*5*4*3*2*1
factorial (6) = 720 = 6*5*4*3*2*1
factorial(5) = 120 = 5*4*3*2*1
factorial(4) = 24 = 4*3*2*1
factorial(3) = 6 = 3*2*1
factorial(2) = 2 = 2*1
factorial(1) =1
Immediately we can identify our base case which is factorial of 1, factorial(1) needs no further computation/calculation .
Looking at the above expressions, we can see factorial(7) is our biggest problem with all those numbers and computations that have to happen, hence we need to break it down.
When studying the expressions you immediately see the overlapping, ie; Factorial(7) has 6*5*4*3*2*1 and factorial(6) has 6*5*4*3*2*1, this is a repetition, wouldn’t it be better if we write it as follows; factorial(7) =7*factorial(6).
Same is applicable with factorial(6) and factorial(5), we can simply say factorial(6)=6* factorial(5).
lets move on to factorial(5) and simplify it as factorial(5)=5*factorial(4).
factorial(4)=4*factorial(3) and factorial(3) can be expressed as 3*factorial(2) until we get to our base case which is factorial(1).
So we can generalize this as factorial(n) = n*factorial(n-1), this means the factorial of whatever value (n)is n times the factorial of 1 less.
The above expressions can also be written as;
factorial of 7 can also be written as 7!=7*6!, with the symbol ! representing factorial.
6!=6*5!
5!=5*4!
4!=4*3!
3!=3*2!
2!=2*1!
1!=1
Thus our recursive case is factorial(n) = n*factorial(n-1), this recursive case will eventually lead us to 1, which is the base case.
let's illustrate this in Python;