Java-gcd

gcd最大公因数,lcm最小公倍数

lcm=a*b/gcd(为了防止数据越界最好写成a/gcd*b)

那么gcd的求法就比较重要了

下面介绍三种求gcd的方法(无需指定大数在前的规则),前两种都是欧几里得算法,最后是穷举法


//	  最大公约数算法
public class Main {
    public static void main(String[] args) {
    	long a=1989,b=1590;
    	System.out.println(gcd1(a,b));
    	System.out.println(gcd2(a,b));
    	System.out.println(gcd3(a,b));
    }
    
//    方法一:欧几里得算法 迭代求值 (时间复杂度O(logN))
    
   private static long gcd1(long a,long b) {
	   while(b!=0)
	   {
		   long temp=a%b;
		   a=b;
		   b=temp;
	   }
	   return a;
   }
   
//    方法二:欧几里得算法 递推法(效率最高)
   
   private static long gcd2(long a,long b){
	   return (a==0?b:gcd2(b%a,a));
   }
   
   
//    方法三:穷举法     (效率低,不推荐)
   private static long gcd3(long a,long b) {
	   long i=a=1;i--)
	   {
		   if(a%i==0&&b%i==0)
			   break;
	   }
	   return i;
   }
    
}



你可能感兴趣的:(Java-gcd)