用于扩展欧几里得算法的Java程序
两个数的 GCD 是除以这两个数的最大数。找到 GCD 的一种简单方法是对两个数字进行因式分解并乘以公因数。
// Java program to demonstrate working of extended
// Euclidean Algorithm
import java.util.*;
import java.lang.*;
class GFG {
// extended Euclidean Algorithm
public static int gcdExtended(int a, int b, int x, int y)
{
// Base Case
if (a == 0) {
x = 0;
y = 1;
return b;
}
int x1 = 1, y1 = 1; // To store results of recursive call
int gcd = gcdExtended(b % a, a, x1, y1);
// Update x and y using results of recursive
// call
x = y1 - (b / a) * x1;
y = x1;
return gcd;
}
// Driver Program
public static void main(String[] args)
{
int x = 1, y = 1;
int a = 35, b = 15;
int g = gcdExtended(a, b, x, y);
System.out.print("gcd(" + a + ", " + b + ") = " + g);
}
}
// Code Contributed by Mohit Gupta_OMG <(0-o)>
输出:
gcd(35, 15) = 5
有关详细信息,请参阅有关基本和扩展欧几里得算法的完整文章!