{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

Recursion1.6

# Recursion1.6 - – n 7 = n 6 n 5 1 = 25 15 1 = 41 – n 8 =...

This preview shows pages 1–5. Sign up to view the full content.

Last Updated 12-01-24 10:12 AM CSE 2011 Prof. J. Elder - 31 - The Golden Ratio Leonardo The Parthenon

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Last Updated 12-01-24 10:12 AM CSE 2011 Prof. J. Elder - 32 - Computing Fibonacci Numbers F 0 = 0 F 1 = 1 F i = F i- 1 + F i- 2 for i > 1. A recursive algorithm (first attempt): Algorithm BinaryFib( k ): Input: Positive integer k Output: The k th Fibonacci number F k if k < 2 then return k else return BinaryFib( k - 1) + BinaryFib( k - 2)
Last Updated 12-01-24 10:12 AM CSE 2011 Prof. J. Elder - 33 - Analyzing the Binary Recursion Fibonacci Algorithm Let n k denote number of recursive calls made by BinaryFib(k). Then n 0 = 1 n 1 = 1 n 2 = n 1 + n 0 + 1 = 1 + 1 + 1 = 3 n 3 = n 2 + n 1 + 1 = 3 + 1 + 1 = 5 n 4 = n 3 + n 2 + 1 = 5 + 3 + 1 = 9 n 5 = n 4 + n 3 + 1 = 9 + 5 + 1 = 15 n 6 = n 5 + n 4 + 1 = 15 + 9 + 1 = 25

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: – n 7 = n 6 + n 5 + 1 = 25 + 15 + 1 = 41 – n 8 = n 7 + n 6 + 1 = 41 + 25 + 1 = 67 . • Note that n k more than doubles for every other value of n k . That is, n k > 2 k/2 . It increases exponentially! Last Updated 12-01-24 10:12 AM CSE 2011 Prof. J. Elder - 34 - A Better Fibonacci Algorithm • Use linear recursion instead: Algorithm LinearFibonacci( k ): Input: A positive integer k Output: Pair of Fibonacci numbers ( F k , F k-1 ) if k = 1 then return ( k, 0) else ( i, j ) = LinearFibonacci( k - 1) return ( i + j, i ) • Runs in O ( k ) time. Last Updated 12-01-24 10:12 AM CSE 2011 Prof. J. Elder - 35 - Binary Recursion • Second Example: The Tower of Hanoi...
View Full Document

{[ snackBarMessage ]}

### Page1 / 5

Recursion1.6 - – n 7 = n 6 n 5 1 = 25 15 1 = 41 – n 8 =...

This preview shows document pages 1 - 5. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online