MATH 302 Lecture 15
« previous | Wednesday, October 19, 2011 | next »
Fibonacci Sequence
Recursive definition
fib1 n
| n == 0 = 0
| n == 1 = 1
| otherwise = fib1 (n-1) + fib1 (n-2)
Easy to describe, but very expensive to evaluate:
fib1(6)
|- fib1(5)
| |- fib1(4)
| | |- fib1(3)
| | | |- fib1(2)
| | | | |- fib1(1)
| | | | `- fib1(0)
| | | `- fib1(1)
| | `- fib1(2)
| | |- fib1(1)
| | `- fib1(0)
| `- fib1(3)
| |- fib1(2)
| | |- fib1(1)
| | `- fib1(0)
| `- fib1(1)
`- fib1(4)
|- fib1(3)
| |- fib1(2)
| | |- fib1(1)
| | `- fib1(0)
| `- fib1(1)
`- fib1(2)
|- fib1(1)
`- fib1(0)
Iterative definition
def fib2 n
return 0 if n == 0
return 1 if n == 1
x,y=0,1
1.upto(n-1) { x,y = y,x+y }
y
end
Counting Problems
Towers of Hanoi
Moving disks from one peg to another, etc. Example: It takes 7 moves to shift 3 disks to another peg.
Conjecture: It takes moves to move disks
Let represent the number of moves for disks
Moving disks takes . Move the last disk to another peg, then move the pegs on top of it:
Look at pattern of values for :
1 | 1 |
2 | 3 |
3 | 7 |
4 | 15 |
This supports the conjecture:
Proof by induction.
Basis step. true.
Inductive step. Assume that for some , . By the recurrence relation, we have
Proving the inductive step. The general result follows by the principle of mathematical induction.
Bit Strings
Count the number of bit strings of length with no consecutive zeros:
Possibilities | |
---|---|
0 | {} = 1 |
1 | {1, 0} = 2 |
2 | {11, 10, 01} = 3 |
3 | {111, 110, 101, 011, 010} = 5 |
4 | {1111, 1110, 1101, 1011, 0111, 1010, 0101, 0110} = 8 |
Constructing a Recurrence Relation
Given a string
For if is a 0, then must be an arbitrary legal n-1 string. If is a 1, then must be a legal n-1 string that ends in a 1. This means that must be a valid n-2 strings (conforming to ).
Count the number of possibilities for the last digit in the string. Get to a point where must be a legal string, then add all of the cases to form the case. If there is ever a case where must be an illegal string, then subtract the number of legal strings from the number of total possibilities