Problem

Consider the problem of finding the greatest common divisor (gcd) of two positive integers...

Consider the problem of finding the greatest common divisor (gcd) of two positive integers a and b. The algorithm presented here is a variation of Euclid’s algorithm, which is based on the following theorem:4

THEOREM. If a and b are positive integers with a > b such that b is not a divisor of a, then gcd(a, b) = gcd(b, a mod b).

This relationship between gcd(a, b) and gcd( b, a mod b) is the heart of the recursive solution. It specifies how you can solve the problem of computing gcd(a, b) in terms of another problem of tire same type. Also, if b does divide a, then b = gcd(a, b?), so an appropriate choice for the base case is (a mod b) = 0. This theorem leads to the following recursive definition:

The following method implements this recursive algorithm:

public static int gcd(int a, int b) {

if (a % b == 0) { // base case

return b;

}

else {

return gcd(b, a % b);

} // end if

} // end gcd

a. Prove the theorem.

b. What happens if b > a?

c. How is tiie problem getting smaller? (That is, do you always approach a base case?) Why is the base case appropriate?

Step-by-Step Solution

Request Professional Solution

Request Solution!

We need at least 10 more requests to produce the solution.

0 / 10 have requested this problem solution

The more requests, the faster the answer.

Request! (Login Required)


All students who have requested the solution will be notified once they are available.
Add your Solution
Textbook Solutions and Answers Search
Solutions For Problems in Chapter 3
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT