C++ 程式實現擴充套件歐幾里得演算法


擴充套件歐幾里得演算法只是計算兩個數的 GCD 的另一種方法。它有額外的變數來計算 ax + by = gcd(a, b)。在計算機程式中使用它更高效

演算法

Begin
   Declare variable a, b, x and y
   gcdExtended(int a, int b, int *x, int *y)
   if (a == 0)
      *x = 0;
      *y = 1;
   return b;
   Take two variables to store the result
   Update x and y using results of recursive call
End

程式碼示例

#include <bits/stdc++.h>
using namespace std;
int gcdExtended(int a, int b, int *x, int *y) {
   if (a == 0) {
      *x = 0;
      *y = 1;
      return b;
   }
   int x1, y1;
   int gcd = gcdExtended(b%a, a, &x1, &y1);
   *x = y1 - (b/a) * x1;
   *y = x1;
   return gcd;
}
int main() {
   int x, y;
   int a = 35, b = 15;
   cout<<"gcd "<<gcdExtended(a, b, &x, &y);
   return 0;
}

輸出

gcd 5

更新於:2019 年 7 月 30 日

2K+ 瀏覽次數

啟動您的職業生涯

透過完成課程獲得認證

開始吧
廣告
© . All rights reserved.