1 / 8

CSci 125 Lecture 16

CSci 125 Lecture 16. Martin van Bommel. Efficiency Trade-off. Recall implementations of IsPrime Final version more efficient Original is more readable and easier to prove correct Prime concern must be correctness Secondary factors are efficiency, clarity, and maintainability

frankreid
Download Presentation

CSci 125 Lecture 16

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CSci 125Lecture 16 Martin van Bommel

  2. Efficiency Trade-off • Recall implementations of IsPrime • Final version more efficient • Original is more readable and easier to prove correct • Prime concern must be correctness • Secondary factors are efficiency, clarity, and maintainability • No “best” algorithm from all perspectives

  3. GCD • Greatest Common Divisor of two numbers • largest number that divides evenly into both • Function to determine GCD of two values int GCD(int x, int y); • e.g. • GCD(49, 35) = 7 • GCD(6, 18) = 6 • GCD(32, 33) = 1

  4. Brute Force GCD int GCD(int x, int y) { int g = x; while (x % g != 0 || y % g != 0) { g--; } return (g); }

  5. Improved GCD int GCD(int x, int y) { int g; if (x < y) g = x; else g = y; while (x % g != 0 || y % g != 0) { g--; } return (g); }

  6. Problems with Brute Force • Poor choice for efficiency • e.g. GCD(10005, 10000) = 5 • Long running loop to find simple answer • Can’t count up! Why? • Other choices?

  7. Euclid’s Algorithm for GCD 1. Divide x by y; call remainder r 2. If r is zero, answer is y. 3. If r is not zero, set x equal to old value of y, set y equal to r, repeat entire process • Difficult to prove correct (see text)

  8. Euclid’s GCD int GCD(int x, int y) { int r; while (TRUE) { r = x % y; if (r == 0) return (y); x = y; y = r; } }

More Related