📜  基本欧几里得算法的Java程序

📅  最后修改于: 2022-05-13 01:58:09.489000             🧑  作者: Mango

基本欧几里得算法的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 gcd(int a, int b)
    {
        if (a == 0)
            return b;
  
        return gcd(b % a, a);
    }
  
    // Driver Program
    public static void main(String[] args)
    {
        int a = 10, b = 15, g;
        g = gcd(a, b);
        System.out.println("GCD(" + a + ", " + b + ") = " + g);
  
        a = 35;
        b = 10;
        g = gcd(a, b);
        System.out.println("GCD(" + a + ", " + b + ") = " + g);
  
        a = 31;
        b = 2;
        g = gcd(a, b);
        System.out.println("GCD(" + a + ", " + b + ") = " + g);
    }
}
// Code Contributed by Mohit Gupta_OMG <(0_o)>
输出:
GCD(10, 15) = 5
GCD(35, 10) = 5
GCD(31, 2) = 1

时间复杂度: O(Log min(a, b))
有关详细信息,请参阅有关基本和扩展欧几里得算法的完整文章!