Recursion. Jordi Cortadella Department of Computer Science

Similar documents
Recursion. Recursion. Mathematical induction: example. Recursion. The sum of the first n odd numbers is n 2 : Informal proof: Principle:

mith College Computer Science Week 13 CSC111 Spring 2018 Dominique Thiébaut

APCS-AB: Java. Recursion in Java December 12, week14 1

Recursion. Dr. Jürgen Eckerle FS Recursive Functions

Recursion (Rosen, 6 th edition, Section 4.3, 4.4)

CSC-140 Assignment 4

CS200: Recursion and induction (recap from cs161)

UNIT 5A Recursion: Basics. Recursion

UNIT 5A Recursion: Basics. Recursion

Functions. CS10001: Programming & Data Structures. Sudeshna Sarkar Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

Recursive Definitions

CMSC 132: Object-Oriented Programming II. Recursive Algorithms. Department of Computer Science University of Maryland, College Park

def F a c t o r i a l ( n ) : i f n == 1 : return 1 else : return n F a c t o r i a l ( n 1) def main ( ) : print ( F a c t o r i a l ( 4 ) )

For loops, nested loops and scopes. Jordi Cortadella Department of Computer Science

Outline. For loops, nested loops and scopes. Calculate x y. For loops. Scopes. Nested loops. Algorithm: repeated multiplication x x x x

Recursive Methods and Problem Solving. Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms

2.3 Recursion 7/23/2015 3:06:35 PM

CS 161 Intro to CS I. Finish Pointers/Start Recursion

Lecture Notes 4 More C++ and recursion CSS 501 Data Structures and Object-Oriented Programming Professor Clark F. Olson

CS302 - Data Structures using C++

Outline. Introduction to Programming (in C++) Algorithms on sequences. Reasoning about loops: Invariants. Maximum of a sequence. Maximum of a sequence

recursive algorithms 1

Algorithmic Methods Tricks of the Trade

8/5/10 TODAY'S OUTLINE. Recursion COMP 10 EXPLORING COMPUTER SCIENCE. Revisit search and sorting using recursion. Recursion WHAT DOES THIS CODE DO?

Chapter 10: Recursive Problem Solving

Recursion. Chapter 2. Objectives. Upon completion you will be able to:

2.3 Recursion. Overview. Mathematical Induction. What is recursion? When one function calls itself directly or indirectly.

Data Structures And Algorithms

Programming with Recursion. What Is Recursion?

Recursion. Let s start by looking at some problems that are nicely solved using recursion. First, let s look at generating The Fibonacci series.

Summary. csci 210: Data Structures Recursion. Recursive algorithms. Recursion. Topics READING:

csci 210: Data Structures Recursion

Chapter 6 Recursion. The Concept of Recursion

Algorithm. Building blocks of algorithm

1.7 Recursion. Department of CSE

Overview. What is recursion? When one function calls itself directly or indirectly.

CSE 214 Computer Science II Recursion

Chapter 15: Recursion

EE 368. Weeks 4 (Notes)

Recursion. Chapter 7. Copyright 2012 by Pearson Education, Inc. All rights reserved

Notes - Recursion. A geeky definition of recursion is as follows: Recursion see Recursion.

We cover recursion in 150. Why do it again in 151?

11/2/2017 RECURSION. Chapter 5. Recursive Thinking. Section 5.1

Department of Computer Science Yale University Office: 314 Watson Closely related to mathematical induction.

CS 112 Introduction to Programming

2.3 Recursion 7/21/2014 5:12:34 PM

Recursive Problem Solving

What is recursion? Recursion. How can a function call itself? Recursive message() modified. contains a reference to itself. Week 7. Gaddis:

What is recursion? Recursion. How can a function call itself? Recursive message() modified. Week 10. contains a reference to itself.

Discussion 2C Notes (Week 5, February 4) TA: Brian Choi Section Webpage:

Introduction to Computers & Programming

CmpSci 187: Programming with Data Structures Spring 2015

Recursion. Chapter 5

26 Feb Recursion. Overview. Greatest Common Divisor. Greatest Common Divisor. Greatest Common Divisor. Greatest Common Divisor

Experiment: The Towers of Hanoi. left middle right

Recursion. EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG

CSC 273 Data Structures

! New mode of thinking. ! Powerful programming paradigm. ! Mergesort, FFT, gcd. ! Linked data structures.

Data Structures and Algorithms(3)

COMP-202: Foundations of Programming. Lecture 13: Recursion Sandeep Manjanna, Summer 2015

COMP-202. Recursion. COMP Recursion, 2013 Jörg Kienzle and others

Counting Problems; and Recursion! CSCI 2824, Fall 2012!

Recursion. Thinking Recursively. Tracing the Recursive Definition of List. CMPT 126: Lecture 10. Recursion

Binary Search. the towers of Hanoi recursive C++ code. sorted vectors of numbers fast power function. when not to use recursion memoization

Recursion. ! When the initial copy finishes executing, it returns to the part of the program that made the initial call to the function.

Solving problems by recursion

Recursion Chapter 17. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

The power of logarithmic computations. Recursive x y. Calculate x y. Can we reduce the number of multiplications?

Extended Introduction to Computer Science CS1001.py

Discussion 2C Notes (Week 5, February 4) TA: Brian Choi Section Webpage:

Test Bank Ver. 5.0: Data Abstraction and Problem Solving with C++: Walls and Mirrors, 5 th edition, Frank M. Carrano

Outline. Introduction to Programming (in C++) Introduction. First program in C++ Programming examples

34. Recursion. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

A function that invokes itself is said to

CSC 8301 Design and Analysis of Algorithms: Recursive Analysis

Lecture 24 Tao Wang 1

Algorithm Analysis. CENG 707 Data Structures and Algorithms

Recursion. Example R1

Induction and Recursion. CMPS/MATH 2170: Discrete Mathematics

Function with default arguments

Recursion LOGO STYLE GUIDE Schools within the University 19

Recursion. Java recursive programming: Writing methods that call themselves to solve problems recursively.

2.3 Recursion. Overview. Greatest Common Divisor. Greatest Common Divisor. What is recursion? When one function calls itself directly or indirectly.

2.3 Recursion. Overview. Greatest Common Divisor. Greatest Common Divisor. What is recursion? When one function calls itself directly or indirectly.

PDF created with pdffactory Pro trial version Recursion

SOFTWARE DEVELOPMENT 1. Recursion 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)

Taking Stock. IE170: Algorithms in Systems Engineering: Lecture 5. The Towers of Hanoi. Divide and Conquer

What is recursion? Recursion. Recursive message() modified. How can a function call itself? contains a reference to itself. Week 10. Gaddis:

CMPSCI 187: Programming With Data Structures. Lecture #15: Thinking Recursively David Mix Barrington 10 October 2012

Identify recursive algorithms Write simple recursive algorithms Understand recursive function calling

Recursion. Recursion is: Recursion splits a problem:

What is Recursion? ! Each problem is a smaller instance of itself. ! Implemented via functions. ! Very powerful solving technique.

Announcements. Recursion and why study it. Recursive programming. Recursion basic idea

What is recursion? Recursion. How can a function call itself? Recursive message() modified. Week 10. contains a reference to itself. Gaddis:

RECURSION. Data Structures & SWU Rachel Cardell- Oliver

Recursion vs Induction

Big Java, Late Objects, Cay Horstmann, Copyright 2013 John Wiley and Sons, Inc. All rights reserved. Towers of Hanoi

Recursion Chapter 3.5

NCS 301 DATA STRUCTURE USING C

Programming II (CS300)

Transcription:

Recursion Jordi Cortadella Department of Computer Science

Recursion Introduction to Programming Dept. CS, UPC 2

Principle: Reduce a complex problem into a simpler instance of the same problem Recursion 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, UPC 3

Mathematical induction: example The sum of the first n odd numbers is n 2 : Informal proof: 5 7 9 2n-1 n 3 1 Introduction to Programming Dept. CS, UPC 4

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

Definition of factorial: Factorial n! = n n 1 n 2 2 1 // 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; } Introduction to Programming Dept. CS, UPC 6

Recursive definition: Factorial n n 1!, n > 0 n! = ቊ 1, n = 0 // Pre: n 0 // Returns n! int factorial(int n) { // recursive solution if (n == 0) return 1; else return n factorial(n - 1); } Introduction to Programming Dept. CS, UPC 7

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

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, UPC 9

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, UPC 10

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, UPC 11

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

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

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, UPC 14

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, UPC 15

Print 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); Basic case: n < b only one digit. Print it. General case: n b Print the leading digits (n/b) Print the last digit (n%b) Introduction to Programming Dept. CS, UPC 16

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 < b) cout << n; else { print_base(n/b, b); cout << n%b; } } Introduction to Programming Dept. CS, UPC 17

A simpler version // Pre: n 0, 2 b 10 // Prints the representation of n in base b void print_base(int n, int b) { if (n >= b) print_base(n/b, b); cout << n%b; } Introduction to Programming Dept. CS, UPC 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) 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. Not allowed! Introduction to Programming Dept. CS, UPC 19

Tower of Hanoi Introduction to Programming Dept. CS, UPC 20

Tower of Hanoi Introduction to Programming Dept. CS, UPC 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, UPC 22

Tower of Hanoi 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) Introduction to Programming Dept. CS, UPC 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, UPC 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, UPC 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 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 Introduction to Programming Dept. CS, UPC 26

Tower of Hanoi Hanoi(1,L,R,M) Hanoi(0,L,M,R) L R Hanoi(2,L,M,R) L M Hanoi(2,L,M,R) Hanoi(0,M,R,L) Hanoi(0,R,L,M) Hanoi(1,R,M,L) R M Hanoi(3,L,R,M) L R Hanoi(0,L,M,R) Hanoi(0,M,R,L) Hanoi(1,M,L,R) M L Hanoi(2,M,R,L) M R Hanoi(2,M,R,L) Hanoi(0,R,L,M) Hanoi(0,L,M,R) Hanoi(1,L,R,M) L R Hanoi(0,M,R,L) Introduction to Programming Dept. CS, UPC 27

Tower of Hanoi Hanoi(1,L,R,M) Hanoi(0,L,M,R) L R Hanoi(2,L,M,R) L M Hanoi(1,R,M,L) Hanoi(0,M,R,L) Hanoi(0,R,L,M) R M Hanoi(3,L,R,M) L R Hanoi(0,L,M,R) Hanoi(0,M,R,L) Hanoi(2,M,R,L) Hanoi(1,M,L,R) M R Hanoi(1,L,R,M) M L Hanoi(0,R,L,M) Hanoi(0,L,M,R) L R Hanoi(0,M,R,L) Introduction to Programming Dept. CS, UPC 28

Tower of Hanoi How many moves do we need for n disks? Moves(n) = 1 + 2 Moves(n-1) n Moves(n) 1 1 2 3 3 7 4 15 5 31 6 63 n 2 n -1 Introduction to Programming Dept. CS, UPC 29

Tower of Hanoi Let us assume that we can move one disk every second. How long would it take to move n disks? n time 1 1s 5 31s 10 17m 3s 15 9h 6m 7s 20 12d 3h 16m 15s 25 1y 23d 8h 40m 31s 30 > 34y 40 > 34,000y 50 > 35,000,000y 60 > 36,000,000,000y Introduction to Programming Dept. CS, UPC 30