Slightly extended learning algorithm Eculid

Extended Euclid's algorithm

Euclid's algorithm

  • Euclidean

  • Computing the greatest common divisor of two numbers
  • \(\text{gcd}(a,\,b) = \text{gcd}(b,\,a\%b)\)

exEuclid algorithm

  • 裴蜀定理:\(\forall a,\,b,\,\,\exists x,\,y, \,\,s.t. \,\,ax+by=\gcd(a,b)\)
  • It can be calculated using the extended Euclid algorithm \ (X \) and \ (Y \)
  • \ (b = 0 \) , the common factor is \ (A \)
  • \ (b \ not = 0 \ ) when, according to the Euclid algorithm, \ (\ text {gcd} ( a, \, b) = \ text {gcd} (b, \, a \% b) \)
  • Shu Pei using Theorem: \ (= AX + BX by '+ (A \% B) Y' \)
  • \(a\%b=a-b\lfloor\frac{a}{b}\rfloor\)
  • That is to say: \ (= AX + BX by '+ (ab & \ lfloor \ FRAC {A} {B} \ rfloor) Y' \)
  • Sort out: ax + by = ay '+ b (x' - \ lfloor \ frac {a} {b} \ rfloor y ')
  • Can be obtained from the above \ (X = Y '\) , \ (Y = X' - \ lfloor \ FRAC {A} {B} \ rfloor Y '\)
  • Then you can write a recursive it!
int exgcd(int a, int b, int &x, int &y){
    if(b == 0){
        x = 1;
        y = 0;
        return a;
    }else{
        int d = exgcd(b, a % b, x, y);
        int tmp = x;
        x = y;
        y = tmp - a / b * y;
        return d;
    }
}

Guess you like

Origin www.cnblogs.com/tongseli/p/11606570.html