码迷,mamicode.com
首页 > 其他好文 > 详细

编程之美2.7——最大公约数

时间:2015-05-19 10:13:12      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:

求两数最大公约数。

【思路】

1.常规:设求最大公约数算法为f(m,n),则f(m,n)=f(n,m%n)(m>n>0).当n==0时,返回m

原理:x=ky+b,则f(x,y)=f(y,b)。

缺点:除法或取余运算代价较大

2.用减法替代取余。即f(m,n)=f(n,m-n)(m>n>0).

缺点:增加了迭代次数。对于一个超大数和一个1,消耗太大。

3.用以为代替除法。

原理:设y=k*y1, x=k*y2,则f(x,y)=k*f(x1,y1);

若x=p*x1,p是素数,且y%p!=0(即y不能被p整除),有f(x,y)=f(p*x1, y)=f(x1,y);

取p=2,则有三种情况:x y均为偶数;x y一偶一奇;x y均为奇数,对于第三种情况,就用思路2,用差来表示。

【codes】

//method1
int
getcomdev1(int a, int b) { if(a<b) return getcomdev(b, a); return (!b)?a:getcomdev1(b, a%b); }
//method2
int getcomdev(int a, int b)
{
    if(a<b)
        return getcomdev(b, a);
    if(b==0)
        return a;
    if(a%2==0&&b%2==0)
        return getcomdev(a>>1, b>>1)<<1;
    if(a%2==0&&b%2!=0)
        return getcomdev(a>>1, b);
    if(a%2!=0&&b%2==0)
        return getcomdev(a, b>>1);
    if(a%2!=0&&b%2!=0)
        return getcomdev(b,a-b);
}

【总结】

1.method1的一句话代码多么简洁

2.method2的各种情况都要考虑到,与2的乘除运算全部用移位替代。

编程之美2.7——最大公约数

标签:

原文地址:http://www.cnblogs.com/ketchups-notes/p/4513668.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!