130 likes | 244 Views
Divide-&-Conquer Algorithms & Recurrence Relations: Selected Exercises. 10. Find f(n) when n = 2 k , where f satisfies the recurrence relation f(n) = f(n/2) + 1 , with f(1) = 1. 10 Solution. We are asked for the value of f . We are given that
E N D
Divide-&-Conquer Algorithms & Recurrence Relations: Selected Exercises
10 Find f(n) when n = 2k, where f satisfies the recurrence relation f(n) = f(n/2) + 1, with f(1) = 1.
10 Solution We are asked for the value of f. We are given that f(n) = f(n/2) + 1, with f(1) = 1, where n = 2k. f(2k) = f(2k-1) + 1, with f(20) = 1. Answer: f(2k) = k + 1. (Proof would be inductive.)
Master Theorem Let f be an increasing function that such that f(n) = a.f(n/b) + c.nd whenever n = bk, where k Z+, a≥ 1, b >1 is an integer, and c, d Rwith c > 0 & d≥ 0. If ( a < bd ) then f(n) is O( nd ) else if ( a = bd ) then f(n) is O( ndlogn ) else if ( a > bd ) then f(n) is O( nlogba ).
10 Solution (2) • If we were interested only in the asymptotic growth rate, we could use the Master Theorem. • For f(n) = f(n/2) + 1 = 1f(n/2) + 1n0 a = 1 b = 2 d = 0 So, a = bd So, f(n) is O(ndlog n) = O(log n).
20 (a) Set up a divide-&-conquer recurrence relation for the # of modularmultiplies (MM) required to compute anmod m, where a, m, n Z+, using the recursive algorithm from Example 3 in Section 4.4. Let b = a mod m. The algorithm then is: • anmod m = ( an/2mod m )2mod m, for even n(1 MM) • anmod m = ([(a(n-1)/2mod m)2mod m]. b) modn, for odd n(2 MMs)
20 (a) Solution The algorithm is: anmod m = ( an/2mod m )2mod m, for even n(1 MM) anmod m = ([(a(n-1)/2mod m)2mod m]. b) modn, for odd n(2 MMs) Let f(n) denote the # of multiplies. For even n, f(n/2) + 1 MM is used. For odd n, f(n/2) + 2 MMs are used. Worst case, f(n) = f(n/2) + 2.
20 (b) Using f(n) = f(n/2) + 2, construct a big-O estimate for the # of modular multiplies used to compute anmod musing the recursive algorithm.
20 (b) Solution Use the Master Theorem: f(n) = a.f(n/b) + c.nd f(n) = f(n/2) + 2 = 1f(n/2) + 2n0 a = 1, b = 2, d = 0. So, a = bd So, f(n) is O(ndlog n) = O(log n).
30 Exercise 30 assumes that f satisfies the conditions of the Master Theorem. Use Exercise 29 to show that, for f(n) = a.f(n/b) + c.nd if a = bd, then f(n) is O( nd log n ). Exercise 29 gives us: If a = bd & n = bk then f(n) = f(1)nd + cnd logbn.
30 Solution To show: f(n) = f(1)nd + cnd logbn is O( nd log n ). So: • f(n) growthclearly is dominated bycnd logbn. • cis a constant. • logbndiffers fromlog2nby only a constant factor. ( log2b ) .logbn= log2( blogbn) = log2n. • cnd logbntherefore isO( nd log n ).
Theorem 1 Let f be an increasing function such that f(n) = a.f(n/b) + c whenever b |n, where a≥ 1, b >1 are integers, & c > 0 is real. If ( a > 1 ) then f(n) is O( nlogba ) If ( a = 1 ) then f(n) is O( logn ). When n = bk where k > 0 is integer, and a > 1, f(n) = C1 nlogba + C2, where C1 = f(1) + c/(a – 1) and C2= – c/(a – 1).