Presentation is loading. Please wait.

Presentation is loading. Please wait.

Recursion Jordi Cortadella Department of Computer Science.

Similar presentations


Presentation on theme: "Recursion Jordi Cortadella Department of Computer Science."— Presentation transcript:

1 Recursion Jordi Cortadella Department of Computer Science

2 Recursion Introduction to Programming© Dept. CS, UPC2

3 Recursion Principle: – Reduce a complex problem into a simpler instance of the same problem Recursion is a concept tightly related to mathematical induction (typically used for proofs on natural numbers): – Proof a base case for the first natural number – Inductive step: proof that validity for n also implies validity for n+1 (domino effect) Introduction to Programming© Dept. CS, UPC3

4 Mathematical induction: example The sum of the first n odd numbers is n 2 : Informal proof: Introduction to Programming© Dept. CS, UPC4 1 3579 … 2n-1 n

5 Mathematical induction: example Base case: it works for n = 1  Inductive step: let us assume it works for n Introduction to Programming© Dept. CS, UPC5

6 Factorial Introduction to Programming© Dept. CS, UPC6 // Pre: n  0 // Returns n! int factorial(int n) { // iterative solution int f = 1; for (int i = n; i > 0; --i) f = fi; return f; }

7 Factorial Introduction to Programming© Dept. CS, UPC7 // Pre: n  0 // Returns n! int factorial(int n) { // recursive solution if (n == 0) return 1; else return nfactorial(n - 1); }

8 Factorial: recursive solution Introduction to Programming© Dept. CS, UPC8 factorial(n)factorial(n) factorial(n-1)factorial(n-1) factorial(n-2)factorial(n-2) factorial(2)factorial(2) 2 factorial(1)factorial(1) 1

9 Recursion Generally, recursive solutions are simpler than (or as simple as) iterative solutions. There are some problems in which one solution is much simpler than the other. Generally, recursive solutions are slightly less efficient than the iterative ones (if the compiler does not try to optimize the recursive calls). There are natural recursive solutions that can be extremely inefficient. Be careful ! Introduction to Programming© Dept. CS, UPC9

10 Recursive design: 3 steps 1. Identify the basic cases in which a simple non-recursive solution can be provided. Example: 0! = 1! = 1. 2. Recursive cases: solve the complex cases in terms of simpler instances of the same problem (domino effect). Example: factorial(n) = n  factorial(n-1). 3. Termination: guarantee that the parameters of the call move closer to the basic cases at each recursive call (the domino chain is not infinite). Example: In the case of a factorial, n-1 is closer to 0 than n. Therefore, we can guarantee that this function terminates. Introduction to Programming© Dept. CS, UPC10

11 Recursive design: termination It is not clear whether the following function terminates: // Pre: n  1 // Returns the number of steps of the Collatz sequence // that starts with n. int Collatz(int n) { // recursive solution if (n == 1) return 0; else if (n%2 == 0) return 1 + Collatz(n/2); else return 1 + Collatz(3n + 1); } The reason is that 3  n+1 is not closer to 1 than n Introduction to Programming© Dept. CS, UPC11

12 Recursion: behind the scenes Introduction to Programming © Dept. CS, UPC12 int factorial(int n) if (n <= 1) return 1; else return n  factorial(n-1); 4... f = factorial(4);... 4 43 3 3 32 int factorial(int n) if (n <= 1) return 1; else return n  factorial(n-1); 2 2 21 1 1 1

13 2 2 21 1 1 2 2 3 3 32 2 2 6 6 4 4 43 6 6 24 Recursion: behind the scenes Introduction to Programming © Dept. CS, UPC13... f = factorial(4);... int factorial(int n) if (n <= 1) return 1; else return n  factorial(n-1); 1 1 1 1 1 2 2 6 6 24

14 Recursion: behind the scenes Each time a function is called, a new instance of the function is created. Each time a function “returns”, its instance is destroyed. The creation of a new instance only requires the allocation of memory space for data (parameters and local variables). The instances of a function are destroyed in reverse order of their creation, i.e. the first instance to be created will be the last to be destroyed. Introduction to Programming© Dept. CS, UPC14

15 Print a number n in base b Design a procedure that prints a number n in base b to cout. Examples: 1024 is 10000000000 in base 2 1101221 in base 3 2662 in base 7 1024 in base 10 Introduction to Programming© Dept. CS, UPC15

16 Print a number n in base b Basic case: n < 10  only one digit. Print it. General case: n  10 – Print the leading digits (n/b) – Print the last digit (n%b) Introduction to Programming© Dept. CS, UPC16 // Pre: n ≥ 0, 2  b  10 // Prints the representation of n in base b void print_base(int n, int b);

17 Write a number n in base b // Pre: n ≥ 0, 2  b  10 // Prints the representation of n in base b void print_base(int n, int b) { if (n < 10) cout << n; else { print_base(n/b, b); cout << n%b; } } Introduction to Programming© Dept. CS, UPC17

18 Tower of Hanoi The puzzle was invented by the French mathematician Édouard Lucas in 1883. There is a legend about an Indian temple that contains a large room with three time-worn posts in it, surrounded by 64 golden disks. To fulfil an ancient prophecy, Brahmin priests have been moving these disks, in accordance with the rules of the puzzle, since that time. The puzzle is therefore also known as the Tower of Brahma puzzle. According to the legend, when the last move in the puzzle is completed, the world will end. It is not clear whether Lucas invented this legend or was inspired by it. (from http://en.wikipedia.org/wiki/Tower_of_Hanoi)http://en.wikipedia.org/wiki/Tower_of_Hanoi Rules of the puzzle: – A complete tower of disks must be moved from one post to another. – Only one disk can be moved at a time. – No disk can be placed on top of a smaller disk. Introduction to Programming© Dept. CS, UPC18 Not allowed !

19 Tower of Hanoi Introduction to Programming© Dept. CS, UPC19

20 Tower of Hanoi Introduction to Programming© Dept. CS, UPC20

21 Tower of Hanoi What rules determine the next move? How many moves do we need? There is no trivial iterative solution. Introduction to Programming© Dept. CS, UPC21

22 Tower of Hanoi Introduction to Programming© Dept. CS, UPC22 Inductive reasoning: assume that we know how to solve Hanoi for n-1 disks Hanoi(n-1) from left to middle (safe: the largest disk is always at the bottom) Move the largest disk from the left to the right Hanoi(n-1) from the middle to the right (safe: the largest disk is always at the bottom)

23 Tower of Hanoi // Pre: n is the number of disks (n≥0). // from, to and aux are the names of the pegs. // Post: solves the Tower of Hanoi by moving n disks // from peg from to peg to using peg aux void Hanoi(int n, char from, char to, char aux) { if (n > 0) { Hanoi(n - 1, from, aux, to); cout << “Move disk from “ << from << “ to “ << to << endl; Hanoi(n - 1, aux, to, from); } Introduction to Programming© Dept. CS, UPC23

24 Tower of Hanoi // Main program to solve the Tower of Hanoi // for any number of disks int main() { int Ndisks; // Read the number of disks cin >> Ndisks; // Solve the puzzle Hanoi(Ndisks, ‘L’, ‘R’, ‘M’); } Introduction to Programming© Dept. CS, UPC24

25 Tower of Hanoi > Hanoi 5 Move disk from L to R Move disk from L to M Move disk from R to M Move disk from L to R Move disk from M to L Move disk from M to R Move disk from L to R Move disk from L to M Move disk from R to M Move disk from R to L Move disk from M to L Move disk from R to M Move disk from L to R Move disk from L to M Move disk from R to M Introduction to Programming© Dept. CS, UPC25 Move disk from L to R Move disk from M to L Move disk from M to R Move disk from L to R Move disk from M to L Move disk from R to M Move disk from R to L Move disk from M to L Move disk from M to R Move disk from L to R Move disk from L to M Move disk from R to M Move disk from L to R Move disk from M to L Move disk from M to R Move disk from L to R

26 Tower of Hanoi Introduction to Programming© Dept. CS, UPC26 Hanoi(3,L,R,M)Hanoi(2,L,M,R)Hanoi(1,L,R,M)Hanoi(0,L,M,R)LRLRHanoi(0,M,R,L)LMLMHanoi(1,R,M,L)Hanoi(0,R,L,M)RMRMHanoi(0,L,M,R)LRLRHanoi(2,M,R,L)Hanoi(1,M,L,R)Hanoi(0,M,R,L)MLMLHanoi(0,R,L,M)MRMRHanoi(1,L,R,M)Hanoi(0,L,M,R)LRLRHanoi(0,M,R,L) Hanoi(2,L,M,R) Hanoi(2,M,R,L)

27 Tower of Hanoi Introduction to Programming© Dept. CS, UPC27 Hanoi(3,L,R,M)Hanoi(2,L,M,R)Hanoi(1,L,R,M)Hanoi(0,L,M,R)LRLRHanoi(0,M,R,L)LMLMHanoi(1,R,M,L)Hanoi(0,R,L,M)RMRMHanoi(0,L,M,R)LRLRHanoi(2,M,R,L)Hanoi(1,M,L,R)Hanoi(0,M,R,L)MLMLHanoi(0,R,L,M)MRMRHanoi(1,L,R,M)Hanoi(0,L,M,R)LRLRHanoi(0,M,R,L)

28 Tower of Hanoi How many moves do we need for n disks? Moves(n) = 1 + 2Moves(n-1) Introduction to Programming© Dept. CS, UPC28 nMoves(n) 11 23 37 415 531 663 n2 n -1

29 Tower of Hanoi Introduction to Programming© Dept. CS, UPC29 ntime 11s 531s 1017m 3s 159h 6m 7s 2012d 3h 16m 15s 251y 23d 8h 40m 31s 30> 34y 40> 34,000y 50> 35,000,000y 60> 36,000,000,000y Let us assume that we can move one disk every second. How long would it take to move n disks?


Download ppt "Recursion Jordi Cortadella Department of Computer Science."

Similar presentations


Ads by Google