Presentation is loading. Please wait.

Presentation is loading. Please wait.

Recursion. Math Review Given the following sequence: a 1 = 1 a n = 2*a n-1 OR a n+1 = 2*a n What are the values of the following? a 2 = a 3 = a 4 =

Similar presentations


Presentation on theme: "Recursion. Math Review Given the following sequence: a 1 = 1 a n = 2*a n-1 OR a n+1 = 2*a n What are the values of the following? a 2 = a 3 = a 4 ="— Presentation transcript:

1 Recursion

2 Math Review Given the following sequence: a 1 = 1 a n = 2*a n-1 OR a n+1 = 2*a n What are the values of the following? a 2 = a 3 = a 4 =

3 What is recursion? circular definition a function call within a function definition “using a function inside itself” Example: a(1) = 1 a(n) = 2*a(n-1) int a(int n) { if (n == 1) return 1; return 2*a(n-1); }

4 The Base Case Every recursive algorithm has a starting/ending  base case What was the base case for the previous example? What would happen if we did not have the base case?

5 Example What is the base case and equation for the following sequence? a 0 = 1 a 1 = 1 a 2 = 2 a 3 = 6 a 4 = 24 a 5 = 120 a 6 = 720

6 Recursive Function Construction 1. Always start with checking the base case 2. Recursively call (use) the function Don’t forget to include any additional calculations

7 Example a 0 = 1 a n = n * a n-1 OR a(0) = 1 a(n) = n * a(n-1) OR factorial(0) = 1 factorial(n) = n * factorial (n-1) int factorial(int n) { if (n == 0) return 1; return n * factorial(n-1); }

8 Tracing a Recursive Function public static void main( String[] args ) { System.out.println( factorial(4) ); } public int factorial(n) { if (n == 0) return 1; return n * factorial(n-1); }

9 Your Turn What is the base case and equation for the following sequence? a 0 = 1 a 1 = 1 a 2 = 2 a 3 = 3 a 4 = 5 a 5 = 8 a 6 = 13

10 Your Turn Implement the recursive function for the fibonacci sequence

11 Fibonacci int fib(int n) { if (n == 0) return 1; if (n == 1) return 1; return fib(n-1) + fib(n-2); }

12 Recursion Advantages elegant solutions often fewer variables and fewer lines of code (LOCs) many problems are best solved using recursion (e.g. factorial, fibonacci)

13 Recursion Disadvantages recursive overhead  slower than iteration tricky to follow


Download ppt "Recursion. Math Review Given the following sequence: a 1 = 1 a n = 2*a n-1 OR a n+1 = 2*a n What are the values of the following? a 2 = a 3 = a 4 ="

Similar presentations


Ads by Google