11.07.2015 Views

Data Structures and Algorithm Analysis - Computer Science at ...

Data Structures and Algorithm Analysis - Computer Science at ...

Data Structures and Algorithm Analysis - Computer Science at ...

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

524 Chap. 16 P<strong>at</strong>terns of <strong>Algorithm</strong>sNow, for any value n there exists k <strong>and</strong> l such th<strong>at</strong>n = km + l where m > l ≥ 0.From the definition of the mod function, we can derive the fact th<strong>at</strong>n = ⌊n/m⌋m + n mod m.Since the LCF is a factor of both n <strong>and</strong> m, <strong>and</strong> since n = km + l, the LCF musttherefore be a factor of both km <strong>and</strong> l, <strong>and</strong> also the largest common factor of eachof these terms. As a consequence, LCF (n, m) = LCF (m, l) = LCF (m, n modm).This observ<strong>at</strong>ion leads to a simple algorithm. We will assume th<strong>at</strong> n ≥ m. Ateach iter<strong>at</strong>ion we replace n with m <strong>and</strong> m with n mod m until we have driven mto zero.int LCF(int n, int m) {if (m == 0) return n;return LCF(m, n % m);}To determine how expensive this algorithm is, we need to know how muchprogress we are making <strong>at</strong> each step. Note th<strong>at</strong> after two iter<strong>at</strong>ions, we have replacedn with n mod m. So the key question becomes: How big is n mod mrel<strong>at</strong>ive to n?n ≥ m ⇒ n/m ≥ 1⇒2⌊n/m⌋ > n/m⇒ m⌊n/m⌋ > n/2⇒⇒n − n/2 > n − m⌊n/m⌋ = n mod mn/2 > n mod mThus, function LCF will halve its first parameter in no more than 2 iter<strong>at</strong>ions.The total cost is then O(log n).16.3.3 M<strong>at</strong>rix Multiplic<strong>at</strong>ionThe st<strong>and</strong>ard algorithm for multiplying two n × n m<strong>at</strong>rices requires Θ(n 3 ) time.It is possible to do better than this by rearranging <strong>and</strong> grouping the multiplic<strong>at</strong>ionsin various ways. One example of this is known as Strassen’s m<strong>at</strong>rix multiplic<strong>at</strong>ionalgorithm.For simplicity, we will assume th<strong>at</strong> n is a power of two. In the following, A<strong>and</strong> B are n × n arrays, while A ij <strong>and</strong> B ij refer to arrays of size n/2 × n/2. Using

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!