educative.io

The solution will cause a runtime error if one of the number equals 0

Hi This Java solution for “Find the Greatest Common Divisor” has a runtime error if one of the two numbers equals 0. Could you please help correct it? Thanks!

Hi @Miaozhen_Zhang ,
Thanks for contacting Educative Team. The reason this function produces a runtime error when one of the numbers is 0 is that the function is implemented recursively and the base case for terminating the recursion is when both numbers are equal. If one of the numbers is 0, the function will never reach the base case and instead, it will keep subtracting the smaller number from the larger number until the larger number becomes negative, which will cause a RuntimeError to occur.

To fix the issue, you can add an additional check at the beginning of the function to handle the case where one of the numbers is 0. For example, you could modify the function as follows:

class Solution {
    public static int gcd(int num1, int num2) {
        // Base cases
        if (num1 == 0){
        return num2;
       }
       if num2 == 0{
        return num1;
       }
        if (num1 == num2) {
            return num1;
        }
        // Recursive case
        if (num1 > num2) {
            return gcd(num1-num2, num2);
        }
        else {
            return gcd(num1, num2-num1);
        }
    }
}

I hope it helps. Happy Learning :blush: