编程之美: 最大公约数

    求最大公约数有很多技巧。

    可以用减法代替求余数。具体实现如下

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#include<iostream>
#include<tuple>
using  namespace std;
/*
写一个程序,求两个正整数的最大公约数,如果两个正整数都很大,有什么简单的算法。
*/


//最大公约数求法:f(42,30)=f(30,12)=f(12,6)=f(6,0)=6

int gcd( int x,  int y)
{
     return (!y) ? x : gcd(y, (x % y));
}

int simplegcd( int x,  int y)
{
     if(y ==  0)
    {
         return x;
    }
     else
    {
         return gcd(y, y % x);
    }
}

int gcd2( int x,  int y)
{
     int big, small, tmp;
     if(x > y)
    {
        big = x;
        small = y;
    }
     else
    {
        big = y;
        small = x;
    }

     if(big - small > small)
    {

        big = big - small;

    }
     else
    {
        tmp = big - small;
        big = small;
        small = tmp;
    }
     return (!small) ? big : gcd(big, small);


}

int gcd3( int x,  int y)
{
     if(x < y)
         return gcd3(y, x);
     if(y ==  0)
         return x;
     else
    {
         return gcd3(x - y, y);
    }
}
bool IsEvent( int x)
{
     if(x %  2 ==  0)
         return  false;
     else
         return  true;
}

int gcd4( int x,  int y)
{
     if(x < y)
         return gcd4(y, x);
     if(y ==  0)
         return x;
     else
    {
         if(IsEvent(x))
        {
             if(IsEvent(y))
            {
                 return (gcd4(x >>  1, y >>  1) <<  1);
            }
             else
            {
                 return (gcd4(x >>  1, y));
            }
        }
         else
        {
             if(IsEvent(y))
            {
                 return (gcd4(x, y >>  1));
            }
             else
            {
                 return (gcd4(x - y, y));
            }
        }
    }

}
/*
int main()
{
    cout<<simplegcd(30,42);
 system("pause");
 return 0;
}*/


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值