Greatest common divisor(gcd)

欧几里得算法求最大公约数

  • If A = 0 then GCD(A,B)=B, since the GCD(0,B)=B, and we can stop.  
  • If B = 0 then GCD(A,B)=A, since the GCD(A,0)=A, and we can stop.  
  • Write A in quotient remainder form (A = B⋅Q + R)
  • Find GCD(B,R) using the Euclidean Algorithm since GCD(A,B) = GCD(B,R)

这里Q是正整数.

Example:

Find the GCD of 270 and 192

  • A=270, B=192
  • A ≠0
  • B ≠0
  • Use long division to find that 270/192 = 1 with a remainder of 78. We can write this as: 270 = 192 * 1 +78
  • Find GCD(192,78), since GCD(270,192)=GCD(192,78)

    A=192, B=78

  • A ≠0
  • B ≠0
  • Use long division to find that 192/78 = 2 with a remainder of 36. We can write this as:
  • 192 = 78 * 2 + 36
  • Find GCD(78,36), since GCD(192,78)=GCD(78,36)

    A=78, B=36

  • A ≠0
  • B ≠0
  • Use long division to find that 78/36 = 2 with a remainder of 6. We can write this as:
  • 78 = 36 * 2 + 6
  • Find GCD(36,6), since GCD(78,36)=GCD(36,6)

    A=36, B=6

  • A ≠0
  • B ≠0
  • Use long division to find that 36/6 = 6 with a remainder of 0. We can write this as:
  • 36 = 6 * 6 + 0
  • Find GCD(6,0), since GCD(36,6)=GCD(6,0)

A=6, B=0

  • A ≠0
  • B =0, GCD(6,0)=6

So we have shown:

GCD(270,192) = GCD(192,78) = GCD(78,36) = GCD(36,6) = GCD(6,0) = 6

GCD(270,192) = 6

应用:

int gcd(int a, int b) {
    while(b){
int r = a % b;
a = b;
b = r;
}
return a; }

 

转载于:https://www.cnblogs.com/klitech/p/5763478.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值