cse101_9_23_11

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

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

View Full Document Right Arrow Icon
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)
Background image of page 1

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

View Full DocumentRight Arrow Icon
Background image of page 2
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. Weve gone from exponential O(F n ) -&gt; polynomial O(n). C. Weve 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 theres a much faster way repeated squaring M -&gt; M 2 -&gt; M 4-&gt; M 8-&gt; -&gt; 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

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 Right Arrow Icon
Ask a homework question - tutors are online