Search code examples
javarecursiongreatest-common-divisor

Why the output of this greatest common divisor program is coming as -1 if the recursive call should stop and return when a or b becomes 0


1.The method takes two arguments for calculating the greatest common divisor. 2.Instead of returning the values of a or b, the program returns -1.

public static int gcd(int a,int b)
    {

        if(a==0 && b>0)
        {
            // returns when a becomes  0
            return b;
        }
        else if(b==0 && a>0)
        {
            //returns when b becomes 0
            return a;

        }
        else if(a>b)
         gcd(b,a%b);
        else 
            gcd(a,b%a);

        return -1;
    }

Solution

  • You need to return the recursive calls too. So no need to return -1

    public static int gcd(int a, int b) {
    
        if (a == 0 && b > 0) {
            // returns when a becomes  0
            return b;
        } else if (b == 0 && a > 0) {
            //returns when b becomes 0
            return a;
    
        } else if (a > b) {
            return gcd(b, a % b);
        } else {
            return gcd(a, b % a);
        }
    }