Download presentation
Presentation is loading. Please wait.
1
Proof Techniques and Recursion
2
Proof Techniques Proof by induction –Step 1: Prove the base case –Step 2: Inductive hypothesis, assume theorem is true for all cases up to limit k –Step 3: Show theorem is true for next case (k+1) Proof by counterexample –Prove a statement false by providing a case where it is not correct Proof by contradiction –Assume theorem is false and show that the assumption implies a known property is false
3
Recursion “A function that is defined in terms of itself is called recursive.” Example: n! 1*2*3*…*(n-1)*n n*factorial of (n-1)
4
Rules of Recursion 1.Base cases. You must always have some bases cases, which can be solved without recursion. 2.Making progress. For the cases that are to be solved recursively, the recursive call must always be to a case that makes progress toward a base case. 3.Design rule. Assume that all the recursive calls work. 4.Compound interest rule. Never duplicate work by solving the same instance of a problem in separate recursive calls.
5
Function: factorial int factorial(int n) { if(n == 1) return 1; else return (n*factorial(n-1)); }
6
Iterative Factorial int factorial(int n) { int i; int product = 1; for(i = n; i > 1; i--) { product = product * i; } return product; }
7
Linear Recursion At most 1 recursive call at each iteration –Example: Factorial General algorithm –Test for base cases –Recurse Make 1 recursive call Should make progress toward the base case Tail recursion –Recursive call is last operation –Can be easily converted (should be!) to iterative
8
Higher-Order Recursion Algorithm makes more than one recursive call Binary recursion –Halve the problem and make two recursive calls –Example? Multiple recursion –Algorithm makes many recursive calls –Example?
9
Example Design a recursive program to produce the following output: 0 0 1 0 1 2 0 1 2 3 0 1 2 3 4 0 1 2 3 0 1 2 0 1 0
10
Analyzing Recursive Functions Factorial –Similar to analyzing a loop Previous example Version 3 of Maximum Subsequence Sum problem (pg. 53)
11
Algorithm find max sum of first half find max sum of second half starting from middle, iterate through list toward beginning and stop when max found return max of first half, second half, and sum of overlap
12
Recurrence T(1) = 1 T(N) = 2T(N/2) + O(N) T(1) = 1, T(2) = 4 = 2*2, T(4) = 12 = 4*3, T(8) = 32 = 8*4, T(16) = 80 = 16*5 T(N) = N*(k+1) -- if N=2 k T(N) = 2 k *(k+1) T(N) = k2 k + 2 k T(N) = logN(N) + N = NlogN + N = O(NlogN)
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.