How to calculate the GCD (greatest common divisor) of two integers using recursion in Java

1 Answer

0 votes
public class MyClass {
    static int getGCD_Recursion(int a, int b) {
        while (a != b) {
            if (a > b) {
                return getGCD_Recursion(a - b, b);
            }
            else {
                return getGCD_Recursion(a, b - a);
            }
        }
        return a;
    }
    public static void main(String args[]) {
        int a = 12, b = 20;
       
        System.out.printf("The GCD (greatest common divisor) of %d and %d is: %d\n", a, b, getGCD_Recursion(a, b));
    }
}




/*
run:
 
The GCD (greatest common divisor) of 12 and 20 is: 4
 
*/

 



answered Jan 12, 2022 by avibootz
edited Jan 12, 2022 by avibootz
...