算法导论 31-1 二进制的gcd算法

33-1(二进制的gcd算法) 与计算余数的执行速度相比,大多数计算机执行减法运算,测试一个二进制整数的奇偶性运算以及折半运算的执行速度都要更快些。本题所讨论的二进制gcd算法中避免了欧几里得算法中对余数的计算过程。

a.证明:如果a和b都是偶数,则gcd(a,b)=2gcd(a/2,b/2).

b.证明:如果a是奇数,b是偶数,则gcd(a,b)=gcd(a,b/2).

c.证明:如果a和b都是奇数,则gcd(a,b)=gcd((a-b)/2,b).

d.设计一个有效的二进制算法,输入整数为a和b(a≥b),并且算法的运行时间为O(lg a).假定每个减法运算,测试奇偶性运算以及折半运算都能在单位时间行。

/*
if a and b are both even, then gcd(a,b)= 2 * gcd(a/2,b/2).
if a is odd and b is even, then gcd(a,b) = gcd(a,b/2).
that if a and b are both odd, then gcd(a,b) = gcd((a-b)/2,b).
Design an efficient binary gcd algorithm for input integers a and b, where
a >= b, that runs in O(lg a) time.
 */
  public static int binaryGcd(int a, int b) {// assume a>=b;
    a = Math.abs(a); // gcd(a,b) = gcd(|a|,|b|) 31.8
    b = Math.abs(b);
    if (a < b) {
      return binaryGcd(b, a);
    }
    if (b == 0) {
      return a;
    }

    if ((a & 1) == 0 && (b & 1) == 0) {// both a and b are even
      int half = binaryGcd(a >> 1, b >> 1);
      return half << 1;
    }
    else if ((a & 1) == 1 && (b & 1) == 0) {// a odd, b even
      return binaryGcd(a, b >> 1);
    }
    else if ((a & 1) == 0 && (b & 1) == 1) {// a even, b odd
      return binaryGcd(a >> 1, b);
    }
    else { // a odd, b odd
      return binaryGcd((a - b) >> 1, b);
    }
  }

  public static void main(String[] args) {
    int gcd = binaryGcd(-21, 15);
    System.out.println("gcd(-21,15)="+gcd);
    int a = 2*3*7*13*5;
    int b = 17*3*14*2*5;
    gcd = binaryGcd(a,b);
    System.out.println("gcd(a,b)="+gcd);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值