GreatestCommonDivisor:gcd可以使用辗转相除法(欧几里得算法)
public class GreatestCommonDivisor { public static void main(String[] args) { int a = 12; int b = 18; System.out.println(gcd(a, b)); } public static int gcd(int a, int b) { if (b == 0) return a; else return gcd(b, a % b); } }模拟过程:
(1)gcd(12,18),return gcd(18, 12)
(2)gcd(18,12), return gcd(12, 6)
(3)gcd(12,6),return gcd(6, 0)
(4)gcd(6,0), return 6
两个数的最大公约数
最新推荐文章于 2021-06-12 21:07:51 发布