最大公约数的快速求法

本题为编程之美中的第2.7题,上面的解法比辗转相除发的时间复杂度要小很多。看完之后用while循环代替了递归重写了一下。

废话少说,上源码:

 1 #include <iostream>
 2 using namespace std;
 3 
 4 int GDC(unsigned long long x, unsigned long long y)
 5 {
 6     unsigned long long deep = 1;
 7     while(y != 0)
 8     {
 9         if (x < y)
10         {
11             x ^= y;
12             y ^= x;
13             x ^= y;
14             continue;
15         }
16         if (x & 0x01 == 0)
17         {
18             if (y & 0x01 == 0)
19             {
20                 x >>= 1;
21                 y >>= 1;
22                 deep <<= 1;
23             }
24             else
25             {
26                 x >>= 1;
27             }
28         }
29         else
30         {
31             if (y & 0x01 == 0)
32             {
33                 y >>= 1;
34             }
35             else
36             {
37                 unsigned long long temp = x - y;
38                 x = y;
39                 y = temp;
40             }
41         }
42     }
43     return deep * x;
44 }
45 
46 int main()
47 {
48     int result = GDC(24, 42);
49     cout << result;
50     return 0;
51 }

运行结果:
24 和 42 的最大公约数 为 6。

转载于:https://www.cnblogs.com/michaelGD/archive/2012/11/28/2792788.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值