今天看了一个最求最大公约数的问题,写了个小程序:
public class MaxDivisor
{
public static int getMaxDivisor(int a, int b)
{
if (a <= 0 || b <= 0)
{
return 0;
}
return getDivisor(a, b);
}
private static int getDivisor(int a, int b)
{
if (a < b)
{
a = a + b;
b = a - b;
a = a - b;
}
if (a % b == 0)
{
return b;
}
return getDivisor(b, a - b);
}
public static void main(String[] args)
{
System.out.println(getMaxDivisor(21, 14));
}
}
{
public static int getMaxDivisor(int a, int b)
{
if (a <= 0 || b <= 0)
{
return 0;
}
return getDivisor(a, b);
}
private static int getDivisor(int a, int b)
{
if (a < b)
{
a = a + b;
b = a - b;
a = a - b;
}
if (a % b == 0)
{
return b;
}
return getDivisor(b, a - b);
}
public static void main(String[] args)
{
System.out.println(getMaxDivisor(21, 14));
}
}