CH 4 - Recursion
CH 4 - Recursion
Recursion
Recursion - Introduction
Disadvantages
if(n<=1)
Return 1;
Return n*fact(n-1);
if(n==0)
Return a;
Return fact(n-1,a*n);
Recursively defined function
● The factorial of a number is the product of all the integers from 1 to that
number. [ex: 5! = 1*2*3*4*5 = 120 ]
● Factorial is not defined for negative integers and the factorial of zero is 1.
f(n) = n*f(n-1) => Recursive case:- the function calls itself, with simpler instance.
Recursively defined function - example [1] - Factorial
factorial(5)
Recursively defined function - ex[2] - Fibonacci Number
● Fibonacci numbers are the numbers appearing in the following integer
sequence: 0,1,1,2,3,5,8,13,21,34,55,89,144, ……………..
● This can be defined mathematically as:
Fn = Fn-1 + Fn-2 with F0=0 and F1=1
Fibonacci as recursive function:
def fibonacci(n):
If n==0:
Return 0
Else if n==1:
Return 1
Else:
Return fibonacci(n-1) + fibonacci(n-2)
Recursively defined function - ex[2] - Fibonacci Number
fibonacci(4):
Recursively defined function - ex[3] - GCD
● GCD or HCF of two numbers is the largest number that divides both of them.
● Ex: GCD of 63 & 42:
The factors of 63 are (7,3) ie: 63 = 7 * 3 * 3
The factors of 42 are (7,3,2) ie: 42 = 7 * 3 * 2
So the GCD of 63 and 42 is 21 [7*3=21]
● The objective of the puzzle is to move the entire stack to the last rod, obeying
the following rules:
○ Only one disk can be moved at a time.
○ Each move consists of taking the upper disk from one of the stacks and placing it on top of
another stack or on an empty rod.
○ No larger disk may be placed on top of a smaller disk.
Recursively defined function - ex[3] - Tower of Hanoi[3]
Recursive Solution to TOH
Function recursiveTOH(n,s,a,d) // n=> number of disks, s=> starting pole,
//a=>intermediate
pole, d=> destination pole.
If n==1 then
Display “move s to d”
Return
recursiveTOH(n-1,s,d,a);
Display “move s to d”
recursiveTOH(n-1,a,s,d);
End function
Recursively defined function - ex[3] - Tower of Hanoi[4]
Case 1: For even number of disks:
1. Make the legal move between pegs A & B (in either direction)
2. Make the legal move between pegs A & C (in either direction)
3. Make the legal move between pegs B & C (in either direction)
4. Repeat until complete
Case 2: For an odd number of disks:
1. Make the legal move between pegs A & C (in either direction)
2. Make the legal move between pegs A & B (in either direction)
3. Make the legal move between pegs B & C (in either direction)
4. Repeat until complete
In either case, a total of 2n -1 moves are required.
Recursively defined function - ex[3] - Tower of Hanoi[5]
Example:
Recursively defined function - ex[3] - Tower of Hanoi[6]
Example:
Applications of Recursion
● Sorting of data
● Solving problems based on tree structure
● Calculating mathematical series and sequences
● Drawing and detecting fractals and graphical objects
Finding efficiency of a recurrence relation