cse101_9_23_11

cse101_9_23_11 - Return F[n B How fast is Fib2 O(n...

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

Analyzing Algorithms 1. Three questions A. Is it correct? B. How fast is it? C. Can we improve it? 2. Example – Fibonacci numbers A. F 0 = 0 F 1 = 1 F n = F n+1 + F n-2 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, … F 30 > 1 million, grows exponentially fast. F n ~ 1.6 n B. Function fib(n): If n < 0: error If n = 0: return 0 If n = 1: return 1 Return fib(n-1) + fib(n-2) How fast is it? T(n) = # of operations to compute fib(n) = T(n-1) + T(n-2) + 1 >= F n growing at least as fast as the n th Fibonacci number. Therefore, running time is at least 1.6 n , aka exponential. Compute F 200 . Time needed >= (at least) 1.6 200 operations. Fastest computer in China – 2500 trillion operations per second, would takes 2 88 seconds Time scales in seconds 2 10 = 17 minutes 2 20 = 12 days 2 30 = 32 years 2 40 = cave paintings 2 51 = big bang Keeps repeating same computation. A better algorithm A. Function fib2(n) Initialize array F[0…n] to 0 … O(n) F[0] = 0. F[1] = 1] ………………. O(1) For I = 2 to n: ……………………. O(1) F[i] = F[i-1] + F[i-2] . . O(n)

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: Return F[n] B. How fast is Fib2? O(n) operations, linear. We’ve gone from exponential O(F n ) -> polynomial O(n). C. We’ve been careless in our runtime accounting. Adding numbers is not O(1) time if the numbers are arbitrarily large. F n ~ 1.6 n , ie O(n) bits long. Adding n-bit numbers takes O(n) time. D. Updated running times Fib: O(nF n ) exponential Fib2: O(n 2 ) polynomial Can we do better? A third algorithm a. Matrix vector form F = 0 F 1 1 F 1 = 0 1 F F 2 = 1 1 F 1 2 F 2 = 0 1 F F 3 = 1 1 F 1 So algorithm = n F n = 0 1 F F n+1 = 1 1 F 1 Time to compute F n is then the time to compute M n . We could compute M, M 2 , M 3 , M 4 , M 5 , … M n But there’s a much faster way repeated squaring M -> M 2 -> M 4-> M 8-> … -> M n Just O(log n) marix multiplications Multiplying n-bit numbers like O(n 2 ) time. Time to compute M n time to compute M n/2 one matrix multiplication T(n) = T(n/2) + O(n 2 )...
View Full Document

This note was uploaded on 01/09/2012 for the course CSE 101 taught by Professor Staff during the Spring '08 term at UCSD.

Page1 / 2

cse101_9_23_11 - Return F[n B How fast is Fib2 O(n...

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

View Full Document
Ask a homework question - tutors are online