80 likes | 90 Views
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
E N D
CSci 125Lecture 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 • No “best” algorithm from all perspectives
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
Brute Force GCD int GCD(int x, int y) { int g = x; while (x % g != 0 || y % g != 0) { g--; } return (g); }
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); }
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?
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)
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; } }