public class Euclid {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println(euclid(100, 10));
System.out.println(euclid(454, 24));
System.out.println(euclid(1020, 104));
System.out.println(euclid(1020, 105));
System.out.println(euclid(1024, 644));
System.out.println(euclid(1111111, 1234567));
System.out.println(euclid(100, 1203000));
}
public static int euclid(int first, int second) {
if (first <= 0 || second <= 0) {
throw new IllegalArgumentException();
}
if(first < second)
{
int temp = second;
second = first;
first =temp;
}
int temp = first % second;
if (temp == 0) {
return second;
} else {
return euclid(second, temp);
}
}
}
定理:gcd(a,b) = gcd(b,a mod b) (a>b 且a mod b 不为0)
证明:a可以表示成a = kb + r,则r = a mod b
假设d是a,b的一个
公约数,则有
d|a,d|b,而r = a - kb,因此d|r
因此d也是(b,a mod b)的
公约数
因此(a,b)和(b,a mod b)的公约数是一样的,其最大公约数也必然相等,得证