2. Recursion and PMI #

Created Saturday 28 December 2019

Problem: Prove that P(x) is true for all x ∈ N. Step 1: **Base Case **- F(x) is true for x = anchor point. Mostly F(0) or F(1) is shown to be true. [ Done by observation ] Step 2: Induction Hypothesis - Assume that F(k) is true for some k in the input range. [ This is your hypothesis, it cannot be challenged until the completion of the next step ] Step 3: **Induction Step **- Prove that F(k+1) is true. [ Just check that this is is sync with the hypothesis value, by assuming F(k) is true ] If Step 3 holds then F(k) is true for all n.

**Reason why it works: **1. We have a base. For a unit part of the ladder, we prove that the next unit is there. This is true for all units, since we used a variable ‘k’. Definitely it is true for the base case. Hence the ladder can be progressed for any k in N.

Example: Using PMI for factorial.

int factorial(int n) // exploded view of the code
{
	if(n==0)
		return 1; 	// Base case
	else
	{
		int smallOutput = factorial(n-1); 	// Induction hypothesis: which is the function itself.
		int output = n * factorial(n-1); 	// this is where we put our hypothesis(i.e assumed solution).
		return output;
	}
}
// A simple version(equivalent to the above)
int factorial(int n)
{
	if(n==0)
		return 1; 	// Base case
	return n * f(n-1); // all temp variable are handled by the compiler
}

Flow of a recursive function #

There are 3 things in a recursive functions, in this order

  1. Anchor condition
  2. Recursive call(s)
  3. Small calculation before return, if any.

Note

Recursion rocks #

Recursion is a popular approach for solving problems because recursive solutions are generally easier to think than their iterative counterparts and the code is also shorter and easier to understand.

Using recursion #

In a nutshell:

  1. Solve the problem using PMI(for the nth case, not extremes).
  2. Write the code.
  3. Dry run it using trees.
  4. Done !!

Intro to Recursion Notes