import java.math.BigInteger;
public class Gcd {
public static int gcd(int a,int b){
return b==0?a:gcd(b,a%b);
}
/**
* gcd(a,b) == gcd(a-b,b)// b == 0 则会元素循环,因此停止
* @param a
* @param b
* @return
*/
public static BigInteger gcd(BigInteger a,BigInteger b){
if(a.compareTo(b)<0)return gcd(b,a);
if(b.compareTo(BigInteger.ZERO)==0)return a;//递归停止条件
return gcd(a.subtract(b),b);
}
/**
* 此方法是上面方法的改进,主要根据下面两条:
* 1. f(x,y) : x = k*x1; y = k*y1 so f(x,y)= k*f(x1,y1);
* 2. x = k*x1 y%k!=0 且k 是质数,so f(x,y) = f(x/k,y);
* 只是把 k 取做了2,如果都为偶数的化,它们的最大公约数为2*f(x/2,y/2);
* 如果有一个为偶数,那么就 f(x,y) = f(x/2,y) or f(x,y/2) 就是那个为偶数的/2
* 如果都为奇数,则调用上面的那个方法 f(x,y) = f(x-y,y);
* @param a
* @param b
* @return
*/
public static int gcd3(int a,int b){
if(a<b)return gcd3(b,a);
if(b==0)return a; // 还是调用上面的,只不过下面的做了一些处理
if(!isOdd(a)){ // a 为偶数
if(!isOdd(b)) // b 为偶数
return gcd3(a>>1,b>>1)<<1;
else return gcd3(a>>1,b);
}else{
if(!isOdd(b))
return gcd3(a,b>>1);
else return gcd3(a-b,b);
}
}
public static boolean isOdd(int a){
return (a&1)!=0;
}
public static void main(String args[]){
System.out.println(gcd(2,4));
System.out.println(gcd(new BigInteger("2"),new BigInteger("4")));
System.out.println(gcd3(2,4));
}
}
编程之美--求最大公约数
最新推荐文章于 2021-02-27 16:41:55 发布