Solution Review: Find the Greatest Common Divisor
This lesson provides a detailed review of the solution to the challenge of the previous lesson.
Solution: Greatest Common Divisor
Press + to interact
class Solution {public static int gcd(int num1, int num2) {// Computing absolute valuenum1 = Math.abs(num1);num2 = Math.abs(num2);// Base caseif (num1 == 0) {return num2;}else if (num2 == 0) {return num1;}// Recursive caseif (num1 > num2) {return gcd(num1 % num2, num2);}else {return gcd(num1, num2 % num1);}}public static void main( String args[] ) {int x = 56;int y = 42;int result = gcd(x, y);System.out.println("The GCD of " + x + " and " + y + " is:");System.out.println(result);}}
Understanding the Code
In the code above, the method gcd
is recursive, since it makes a recursive call in the method body. Below is an explanation of the code above.
Driver Method
In the
main()
code, we have defined three integer variables:x
,y
andresult
.The variable
result
, stores the greatest common divisor ofx
andy
, returned by thegcd
method. ...
Access this course and 1400+ top-rated courses and projects.