求最大公约数的欧几里德算法(Euclid's Algorithm)

 求最大公约数的欧几里德算法(Euclid's Algorithm)
算法主要基于两条规则:
1.If b|a then gcd(a, b) = b.
2.If a = bt + r, for integers t and r, then gcd(a, b) = gcd(b, r).
定理gcd(a,b) = gcd(b,a mod b)
例如:Let a = 2322, b = 654.

2322 = 654*3 + 360    gcd(2322, 654) = gcd(654, 360)
654 = 360*1 + 294    gcd(654, 360) = gcd(360, 294)
360 = 294*1 + 66    gcd(360, 294) = gcd(294, 66)
294 = 66*4 + 30    gcd(294, 66) = gcd(66, 30)
66 = 30*2 + 6    gcd(66, 30) = gcd(30, 6)
30 = 6*5    gcd(30, 6) = 6

所以, gcd(2322,654) = 6.


证明: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)的公约数
 
 假设d 是(b,a mod b)的公约数,则
 d | b , d |r ,但是a = kb +r
 因此d也是(a,b)的公约数
 
 因此(a,b)和(b,a mod b)的公约数是一样的,其最大公约数也必然相等,
/*-----------------------------------------------------------------
//  Computes and returns the greatest common divisor of the two
//  positive parameters. Uses Euclid's algorithm.
//Euclid_test.java
-----------------------------------------------------------------*/
public class Euclid_test{
    private static int gcd (int num1, int num2){
        while (num1 != num2)
           if (num1 > num2)
              num1 = num1 - num2;
           else
              num2 = num2 - num1;

        return num1;
   }
 
    public static void main(String[] args){
  Integer B = new Integer(args[0]);
  Integer C = new Integer(args[1]);
  int b=B.intValue();
  int c=C.intValue();
  int a=gcd(b,c);
  System.out.printf("The inputed numbers:"+b+"and"+c+"/n");
  System.out.printf("The greatest common measure is"+a+"/n");
  }
 
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++
//javac Euclid_test.java
//java  Euclid_test  2322 654
+++++++++++++++++++++++++++++++++++++++++++++++++++++*/

推论1:对于(a,b)存在两个整数s和t使得a*s+b*t=gcd(a,b)
(例如2322×20+654×(-71)=6)用Eulen(a,b)表示(a,b)的
Euclidean algorithm 的步长,则Eulen(2322, 654) = 6,Eulen(30, 6) = 1

证明:1)假设,a>b,如果Eulen(a,b)=1,即a=b*u,u是整数,则
        a+(1-u)*b=b=gcd(a,b).让s=1,t=1-u.得证。
     2)假设推论对所有的Eulen(a,b)设Eulen(a,b)=n,加上上面算法的第一步,即a=b*u+r.
Eulen(b,r)=n-1.有归纳假设,存在这样得x,y,使得
b*x+r*y=gcd(b,r)=gcd(a,b).最后,b*(x-u*y)+a*y=gcd(a,b)
其中s=x-u*y,t=y.

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
推论2:对于互质的两个数a和b,存在这样得s和t使得a*s+b*t=1,这个推论也非

常重要,
推论3:a存在模p的乘法逆元的充要条件是gcd(a,p) = 1
(对于整数a、p,如果存在整数b,满足ab mod p =1,则说,b是a的模p乘法逆

元。)

       

你可能感兴趣的:(java)