Question: Write a static method named gcd that accepts two integers as parameters and returns the greatest common divisor (GCD) of the two numbers. The greatest

Write a static method named gcd that accepts two integers as parameters and returns the greatest common divisor (GCD) of the two numbers. The greatest common divisor 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 is to use Euclid's algorithm, which states the following:

GCD(a, b) = GCD(b, a % b)

GCD(a, 0) = Absolute value of a

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

Test your code with the following code file:

public class TestGCD {

public static void main(String[] args) {

System.out.println("GCD of 27 and 6 is " + gcd(27, 6)); // 3

System.out.println("GCD of 24 and 84 is " + gcd(24, 84)); // 12

System.out.println("GCD of 38 and 7 is " + gcd(38, 7)); // 1

System.out.println("GCD of 45 and 105 is " + gcd(45, 105)); // 15

System.out.println("GCD of 1 and 25 is " + gcd(1, 25)); // 1

System.out.println("GCD of 25 and 1 is " + gcd(25, 1)); // 1

System.out.println("GCD of 0 and 14 is " + gcd(0, 14)); // 14

System.out.println("GCD of 14 and 0 is " + gcd(14, 0)); // 14

}

// your code goes here

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!