计算两个正整数的最大公约数和最小公倍数

计算两个正整数的最大公约数和最小公倍数

 1 package huawei;
 2 
 3 import java.math.BigInteger;
 4 
 5 public final class Demo {
 6     
 7     // 功能:获取两个整数的最大公约数
 8     // 输入:两个整数
 9     // 返回:最大公约数
10     public static long getMaxDivisor(long lFirstInput, long lSecondInput)
11     {
12         long x = lFirstInput;
13         long y = lSecondInput;
14         
15         if(x==y) {return x;}
16         else if(x>y) {
17             return get1(x,y);
18         }else {
19             return get1(y,x);
20         }
21     }
22     
23     
24     
25     // 功能:获取两个整数的最小公倍数
26     // 输入:两个整数
27     // 返回:最小公倍数
28     //根据  a*b = gcd(a,b)*lcm(a,b)  gcd为最大公约数 lcm最小公倍数
29     public static long getMinMultiple(long lFirstInput, long lSecondInput)
30     {
31         long x = lFirstInput;
32         long y = lSecondInput;
33         
34         long maxdiv = getMaxDivisor(x,y);//最大公约数
35         
36         //用到了大数类
37         BigInteger a =BigInteger.valueOf(x);
38         BigInteger b =BigInteger.valueOf(y);
39         BigInteger c =BigInteger.valueOf(maxdiv);
40         BigInteger d =(a.multiply(b)).divide(c);
41        
42         return d.longValue();
43     }
44 
45     /**
46      * 欧几米德原理求最小公约数
47      * 条件是a>b>0
48      * */
49     public static long get1(long a,long b) {
50         long x = a;
51         long y = b;
52         
53         if(y==0) 
54         {
55             return x;
56         }
57         
58         else
59         {
60             long temp = (x % y);//temp保存余数
61             
62             x = y;//把除数当被除数
63             
64             y =temp;//把余数当除数
65             
66         return    get1(x,y);
67             
68         }
69         
70     }
71 }
原文地址:https://www.cnblogs.com/hewenwu/p/3669717.html