Number Theory - extended Euclidean

Extended Euclid:

 

  Before looking at the extended Euclidean we should understand gcd, which is the greatest common divisor algorithm

  Let us look at the following code

  int gcd(int a,int b){

    if(b==0) return a;

    else return gcd(b,a%b);

  }

  Of course it is written more simply written ternary operator, reducing the code length

  int gcd(int a,int b){ return b==0?a:gcd(b,a%b); } 

  This method becomes Euclidean

  The following reasoning

  Two numbers are given assuming a = 16, b = 12;

  Seeking the greatest common divisor of two numbers

  Start the simulation calculation process {

    b!=0

    Returns a = 12, b = 4;

    b!=0

    Returns a = 4, b = 0

    b=0

    Gives a = 4

    Indeed the greatest common divisor 

  }

  That mathematical proof of it

  Provided a / b == k .... r thus be obtained r = ak * b; where a is the dividend, b is the divisor, k is the supplier, r is the remainder

  Setting c = gcd (a, b)

  I.e., c is the greatest common divisor of a and b

  We may assume that a = m * c, b = n * c;

  Available equation r = ak * b = mc-k * nc = c (m-kn);

  Then lists gcd (b, r);

  Therefore, r = c (m-kn);

  C can be obtained by a factor of r

  Available m-kn with n mutual contradiction by the quality

  Available gcd (b, r) = c;

  Therefore, gcd (a, b) = gcd (b, r)

  QED

  Wonderful wonderful ah ~ ~ ~ ~ ~ ~

  Then get to the point that

  Extended Euclid

  Algorithm itself can be used to solve variable equation

  It can also be used to inverse yuan

  Also can be used to solve linear congruence equation

  First introduced first use

 1. Indefinite extension Euclid solving equations

  I.e. dualistic simple indeterminate equation ax + by = m;

  But we can change the formula it (anyway formula ignorant)

  According to Baidu available

  ax + by = gcd (a, b) a solution, but zkc tell us chiefs solution is not unique

  Provided ax + by = gcd (a, b) * k

  得 ax+by=d, gcd(a,b)|d;

  gcd (a, b) | d denotes d divisible gcd (a, b);

  When x = 1, y = 0 when

  a=gcd(a,b);

  我们可以靠递归退回x,y到本身

  即可得出答案

   网上大佬的论证

    当 b=0 时,gcd(a,b)=a,此时 x=1 , y=0

         当 b!=0 时,

         设 ax1+by1=gcd(a,b)=gcd(b,a%b)=bx2+(a%b)y2

         又因 a%b=a-a/b*b

         则 ax1+by1=bx2+(a-a/b*b)y2

    ax1+by1=bx2+ay2-a/b*by2

    ax1+by1=ay2+bx2-b*a/b*y2

    ax1+by1=ay2+b(x2-a/b*y2)

    解得 x1=y2 , y1=x2-a/b*y2

    因为当 b=0 时存在 x , y 为最后一组解

    而每一组的解可根据后一组得到

    所以第一组的解 x , y 必然存在

  代码

  void exgcd(int a,int b){

    if(b==0){

      x=1;

      y=0;

      return;

    }

    exgcd(b,a%b);

    k=x;

    x=y;

    y=k-a/b*y;

    return;

  }

  end;

·

  

Guess you like

Origin www.cnblogs.com/liuhailin/p/11008714.html