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));
}
}
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;
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.