天天看點

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

繼續閱讀