最大公约数
来源:互联网 发布:虚拟专用网vpn 软件 编辑:程序博客网 时间:2024/06/05 06:36
测试代码:
public class GetGCD { public static void main(String[] args) { // TODO Auto-generated method stub int x = 42; int y = 30; System.out.println(gcd1(x, y)); System.out.println(gcd2(x, y)); System.out.println(gcd3(x, y)); } private static int gcd3(int x, int y) { // TODO Auto-generated method stub if (x < y) { return gcd3(y, x); } if (y == 0) { return x; } else { if (x % 2 == 0) { if (y % 2 == 0) { return gcd3(x >> 1, y >> 1) << 1; } else { return gcd3(x >> 1, y); } } else { if (y % 2 == 0) { return gcd3(x, y >> 1); } else { return gcd3(x - y, y); } } } } private static int gcd2(int x, int y) { // TODO Auto-generated method stub if (x < y) { return gcd2(y, x); } if (y == 0) { return x; } else { return gcd2(x - y, y); } } // 解法一 private static int gcd1(int x, int y) { // TODO Auto-generated method stub return (y == 0) ? x : gcd1(y, x % y); }}
测试结果:
好了结束了!我觉得书上的解释是完美的,所以全是图片。
0 0