Important Notice:

Practice-It will be discontinued as of November 1st, 2024. After this date, the website will remain online for a transitional period, but login will be restricted to University of Washington NetID authentication. This marks the next phase towards the platform's full retirement. Thank you for your use and support of the application over the years.

If you are looking for an alternative, a similar tool, CodeStepByStep, was developed independently by the original author of Practice-It, and is available at codestepbystep.com**

logo Practice-It logo

BJP3 Exercise 5.2: gcd

Language/Type: Java method basics mod while loops
Author: Leslie Ferguson (on 2013/04/01)

Write a method named gcd that accepts two integers as parameters and returns the greatest common divisor of the two numbers. The greatest common divisor (GCD) of two integers a and b is the largest integer that is a factor of both a and b. The GCD of any number and 1 is 1, and the GCD of any number and 0 is that number.

One efficient way to compute the GCD of two numbers is to use Euclid's algorithm, which states the following:

GCD(A, B) = GCD(B, A % B)
GCD(A, 0) = Absolute value of A

In other words, if you repeatedly mod A by B and then swap the two values, eventually B will store 0 and A will store the greatest common divisor.

For example: gcd(24, 84) returns 12, gcd(105, 45) returns 15, and gcd(0, 8) returns 8.

Type your solution here:


This is a method problem. Write a Java method as described. Do not write a complete program or class; just the method(s) above.

You must log in before you can solve this problem.


Log In

If you do not understand how to solve a problem or why your solution doesn't work, please contact your TA or instructor.
If something seems wrong with the site (errors, slow performance, incorrect problems/tests, etc.), please

Is there a problem? Contact a site administrator.