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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP