Discrete Mathematics Lecture 10 Rubya Afrin Lecturer Northern University of Business and Technology
2 Recursion
Recursive Definitions Recursion is a principle closely related to mathematical induction. In a recursive definition , an object is defined in terms of itself. We can recursively define sequences , functions and sets . 3
Recursively Defined Sequences Example: The sequence {a n } of powers of 2 is given by a n = 2 n for n = 0, 1, 2, … . The same sequence can also be defined recursively : a = 1 a n+1 = 2a n for n = 0, 1, 2, … Obviously, induction and recursion are similar principles. 4
Recursively Defined Functions We can use the following method to define a function with the natural numbers as its domain: Specify the value of the function at zero. Give a rule for finding its value at any integer from its values at smaller integers. Such a definition is called recursive or inductive definition . 5
Recursive Algorithms An algorithm is called recursive if it solves a problem by reducing it to an instance of the same problem with smaller input. Example I: Recursive Euclidean Algorithm procedure gcd(a, b: nonnegative integers with a < b) if a = 0 then gcd(a, b) := b else gcd(a, b) := gcd(b mod a, a) 9
Recursive Algorithms Example II: Recursive Fibonacci Algorithm procedure fibo(n: nonnegative integer) if n = 0 then fibo(0) := 0 else if n = 1 then fibo(1) := 1 else fibo(n) := fibo(n – 1) + fibo(n – 2) 10
Recursive Algorithms procedure iterative_fibo(n: nonnegative integer) if n = 0 then y := 0 else begin x := 0 y := 1 for i := 1 to n-1 begin z := x + y x : = y y := z end end {y is the n-th Fibonacci number} 12
Recursive Algorithms For every recursive algorithm, there is an equivalent iterative algorithm. Recursive algorithms are often shorter, more elegant, and easier to understand than their iterative counterparts. However, iterative algorithms are usually more efficient in their use of space and time. 13