天天看点

C语言之linux内核实现最大公约数算法

最大公约数算法,又称欧几里德算法,至今已有几千年的历史了。在我们开始学习c语言的时候最常用的算法就是辗转相除法,其实在linux内核中,内核也是使用这样的方法实现两数最大公约数的计算。

     两个整数的最大公约数是能够同时整除它们的最大的正整数。辗转相除法基于如下原理:两个整数的最大公约数等于其中较小的数和两数的相除余数的最大公约数。

      例如,252和105的最大公约数是21(252

= 21 × 12;105 = 21 × 5);

      算法原理:

设两数为a、b(b<a),用gcd(a,b)表示a,b的最大公约数,r=a (mod b) 为a除以b以后的余数,k为a除以b的商,即a÷b=k.......r。辗转相除法即是要证明gcd(a,b)=gcd(b,r)。

第一步:令c=gcd(a,b),则设a=mc,b=nc

第二步:根据前提可知r =a-kb=mc-knc=(m-kn)c

第三步:根据第二步结果可知c也是r的因数

第四步:可以断定m-kn与n互质【否则,可设m-kn=xd,n=yd (d>1),则m=kn+xd=kyd+xd=(ky+x)d,则a=mc=(ky+x)dc,b=nc=ycd,故a与b最大公约数成为cd,而非c,与前面结论矛盾】

从而可知gcd(b,r)=c,继而gcd(a,b)=gcd(b,r)。

http://home.ebrun.com/u-1120007.html

http://home.ebrun.com/u-1120008.html

http://home.ebrun.com/u-1120009.html

http://home.ebrun.com/u-1120011.html

http://home.ebrun.com/u-1120015.html

http://home.ebrun.com/u-1120013.html

http://home.ebrun.com/u-1120021.html

http://home.ebrun.com/u-1120019.html

http://home.ebrun.com/u-1120016.html

http://home.ebrun.com/u-1120024.html

http://home.ebrun.com/u-1120012.html

http://home.ebrun.com/u-1120023.html

http://home.ebrun.com/u-1120025.html

http://home.ebrun.com/u-1120022.html

http://home.ebrun.com/u-1120018.html

http://home.ebrun.com/u-1120020.html

http://home.ebrun.com/u-1120014.html

http://home.ebrun.com/u-1120010.html

http://home.ebrun.com/u-1120017.html

http://home.ebrun.com/u-1120031.html

http://home.ebrun.com/u-1120032.html

http://home.ebrun.com/u-1120033.html

http://home.ebrun.com/u-1120034.html

http://home.ebrun.com/u-1120035.html

http://home.ebrun.com/u-1120036.html

http://home.ebrun.com/u-1120038.html

http://home.ebrun.com/u-1120037.html

http://home.ebrun.com/u-1120039.html

http://home.ebrun.com/u-1120041.html

http://home.ebrun.com/u-1120043.html

http://home.ebrun.com/u-1120053.html

http://home.ebrun.com/u-1120051.html

http://home.ebrun.com/u-1120047.html

http://home.ebrun.com/u-1120044.html

http://home.ebrun.com/u-1120045.html

http://home.ebrun.com/u-1120042.html

http://home.ebrun.com/u-1120050.html

http://home.ebrun.com/u-1120054.html

http://home.ebrun.com/u-1120048.html

http://home.ebrun.com/u-1120052.html

http://home.ebrun.com/u-1120061.html

http://home.ebrun.com/u-1120056.html

http://home.ebrun.com/u-1120062.html

http://home.ebrun.com/u-1120040.html

http://home.ebrun.com/u-1120057.html

http://home.ebrun.com/u-1120055.html

http://home.ebrun.com/u-1120059.html

http://home.ebrun.com/u-1120064.html

http://home.ebrun.com/u-1120060.html

继续阅读