我正在使用二进制方法来计算两个分数的 GCD,该方法工作得非常好,除非我将某些数字相减。
我假设这是因为,例如,当我从 1/6 中减去 2/15 时,GCD 有一个重复的数字或类似的东西,尽管我可能是错的。
//The following lines calculate the GCD using the binary method
if (holderNum == 0)
{
gcd = holderDem;
}
else if (holderDem == 0)
{
gcd = holderNum;
}
else if ( holderNum == holderDem)
{
gcd = holderNum;
}
// Make "a" and "b" odd, keeping track of common power of 2.
final int aTwos = Integer.numberOfTrailingZeros(holderNum);
holderNum >>= aTwos;
final int bTwos = Integer.numberOfTrailingZeros(holderDem);
holderDem >>= bTwos;
final int shift = Math.min(aTwos, bTwos);
// "a" and "b" are positive.
// If a > b then "gdc(a, b)" is equal to "gcd(a - b, b)".
// If a < b then "gcd(a, b)" is equal to "gcd(b - a, a)".
// Hence, in the successive iterations:
// "a" becomes the absolute difference of the current values,
// "b" becomes the minimum of the current values.
if (holderNum != gcd)
{
while (holderNum != holderDem)
{
//debuging
String debugv3 = "Beginning GCD binary method";
System.out.println(debugv3);
//debugging
final int delta = holderNum - holderDem;
holderNum = Math.min(holderNum, holderDem);
holderDem = Math.abs(delta);
// Remove any power of 2 in "a" ("b" is guaranteed to be odd).
holderNum >>= Integer.numberOfTrailingZeros(holderNum);
gcd = holderDem;
}
}
// Recover the common power of 2.
gcd <<= shift;
那是我用来完成此操作的代码,调试消息将永远打印出来。
有没有办法在它卡住时作弊,或者设置一个例外?