我似乎无法将以下算法成功转换为Java,请原谅可怕的图片质量,但我正在研究的问题是:
我曾尝试使用以下代码来表示欧几里德算法,但它似乎不起作用。我真的不知道如何用Java代码表示它。有什么帮助吗?
public static int gcd(int x, int y) {
if (y == 0) {
return x;
} else if (x >= y && y > 0) {
return gcd(y, (x % y));
}
}
谢谢。
答案 0 :(得分:6)
x和y之间没有任意顺序。
答案 1 :(得分:4)
您的代码不完整!
如果x < y
怎么办?您的代码不会返回值!
本书未提及的是函数的两个参数不一定需要按降序排列(即x >= y
)。你需要做的是考虑这个事实来计算gcd
。
您只需执行以下操作:
public static int gcd ( int x , int y )
{
if ( y == 0 )
return x;
else if ( x >= y && y > 0)
return gcd ( y , x % y );
else return gcd ( y , x ); // if x < y then go ahead and switch them around.
}
答案 2 :(得分:2)
你快到了。您需要考虑y > x
时会发生什么,并从最终else
分支返回结果(提示:x
和y
可以自由切换位置。)
答案 3 :(得分:1)
你快到了。
您的代码无法编译,因为没有从函数返回的 catch all 子句。
这实际上取决于您是否要将y
的负值传递给此函数。如果您只期望正值,则抛出异常。
public static int gcd(int x, int y) {
if (y == 0) {
return x;
} else if (x >= y && y > 0) {
return gcd(y, (x % y));
}
throw
new IllegalArgumentException(
String.format(
"Unexpected values for x(%d) and y(%d)",
Integer.valueOf( x ),
Integer.valueOf( y )
)
);
}
答案 4 :(得分:0)
以下是我所说的负数:
public static int gcd(int x, int y)
{
if (y == 0)
return x;
if (x < 0)
return gcd(x * -1, y); //turns the first parameter to a positive if it's initally negative
if (y < 0)
return gcd(x, y * -1); //turns the second parameter to a positive if it's initally negative
if (y <= x && x % y == 0)
return y;
return gcd(y, x%y);
}
注意负数,如果你试图找到最大公约数,并且任何一个数都是负数,你可以将它改为正数,结果也是一样。
如果两个数字都是负数,那么我不确定gcd应该是什么。 1? -1? idk所以我把它留了出来。我刚才的代码就好像它们都是正面的。