Question

I am writing a program that uses Euclids algorithm of GCD(a, b) = GCD(b, r) r = a%b. I wrote a method that should return an integer for the main method to spit out, yet when I call for it to do this it says that it is not returning an integer. Here is the code

public class Euclid {

    public static int GCD(int a, int b)
    {
        while (b != 0)
        {
            int r = a%b;
            System.out.println("(" +a+ "," +b+ ")");
            b = r;
            a = b;
            if(b == 0)
            {
                return a;
            }
        }
    }
    public static void main(String[] args)
    {
        System.out.println(GCD(36, 20));    
    }
}
Was it helpful?

Solution

In the code if b == 0 it will not return an int or any value for that matter. You must handle this condition, most likely by specifying a default return value.

  public static int GCD(int a, int b)
    {
        while (b != 0)
        {
            int r = a%b;
            System.out.println("(" +a+ "," +b+ ")");
            b = r;
            a = b;
            if(b == 0)
            {
                return a;
            }
        }
        return 0;
    }

OTHER TIPS

The compiler can't tell that your method will eventually reach the b == 0 condition and return. You can refactor it to:

    int ret = 1;
    while (b != 0)
    {
        int r = a%b;
        System.out.println("(" +a+ "," +b+ ")");
        b = r;
        a = b;
        if(b == 0)
        {
            ret = a;
            break;
        }
    }
    return ret;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top