Introductiontothealgorithm
TheEuclideanalgorithmisanalgorithmusedtofindthegreatestcommondivisoroftwopositiveintegers.TheancientGreekmathematicianEuclidfirstdescribedthisalgorithminhisbook"TheElements",soitwasnamedEuclid'salgorithm.
TheextendedEuclideanalgorithmcanbeusedinfieldssuchasRSAencryption.
Ifyouneedtorequestthegreatestcommondivisorofthetwopositiveintegers1997and615,useEuclid'salgorithmtoproceedlikethis:
1997/615=3(theremaining152)
615/152=4(Remaining7)
152/7=21(Remaining5)
7/5=1(Remaining2)
5/2=2(remaining1)
2/1=2(remaining0)
Sofar,thegreatestcommondivisoris1
Repeatthedivisionoperationwiththedivisorandremainder.Whentheremainderis0,takethedivisorofthecurrentformulaasthegreatestcommondivisor,sothegreatestcommondivisorof1997and615isobtained.
Proofofcalculation
Thecalculationprincipledependsonthefollowingtheorem:
Theorem:ThegreatestcommondivisoroftwointegersisequaltothesmallernumberandtwoThegreatestcommondivisoroftheremainderafterdividinganumber.TheGreatestCommonDivisorisabbreviatedasGCD.
gcd(a,b)=gcd(b,amodb)(Let'sseta>bandr=amodb,risnot0)
ProofMethodOne
acanbeexpressedasa=kb+r(a,b,k,rareallpositiveintegers,andr
Assumingdisacommondivisorofa,b,markMaked|a,d|b,thatis,bothaandbcanbedivisiblebyd.
Andr=a-kb,dividebothsidesbydatthesametime,r/d=a/d-kb/d,Fromtherightsideoftheequation,wecanseethatm=r/disaninteger,sod|r
Sodisalsothecommondivisorofb,amodb.
Because(a,b)Ifthecommondivisorof(b,amodb)isequal,thegreatestcommondivisorisalsoequal,andtheproofisobtained.
Proof2
Assumingc=gcd(a,b),Thentherearem,n,sothata=mc,b=nc;
Letr=amodb,thatis,thereisk,sothatr=a-kb=mc-knc=(m-kn)c;
Sogcd(b,amodb)=gcd(b,r)=gcd(nc,(m-kn)c)=gcd(n,m-kn)c;
Thencisthecommondivisorofbandamodb;
Assumingd=gcd(n,m-kn),thentherearex,y,sothatn=xd,m-kn=yd;som=yd+kn=yd+kxd=(y+kx)d;
soa=mc=(y+kx)dc,b=nc=xdc;wecangetgcd(a,b)=gcd((y+kx)dc,xdc)=dc;
Becausegcd(a,b)=c,sod=1;
gcd(n,m-kn)=1.
Note:Thetwomethodsaredifferent.
Principleofthealgorithm
Lemma1.3.1Ifa,banda=bh+r,whereh,r,thengcd(a,b)=gcd(b,r).
Proof.Assumed1=gcd(a,b)andd2=gcd(b,r),weprovethatd1|d2andd2|d1,sowecanuseProposition1.1.3⑵andd1,d2arepositivenumberstoprovethatd1=d2.
Becaused1|aandd1|buseCorollary1.1.2,weknowthatd1|a-bh=r.Becaused1|b,d1|randd2=gcd(b,r),itisdeterminedbyProposition1.2.5Knowd1|d2.Ontheotherhand,becaused2|bandd2|r,d2|bh+r=a.Sod2|d1canbeobtained.
Lemma1.3.1tellsusthatwhena>b>0,werequirethegreatestcommondivisorofaandb.Wecanfirstdivideabyb.Iftheremainderisr,thena,bisThegreatestcommonfactorisequaltothegreatestcommonfactorofbandr.Becauser<b<a,ofcoursethecalculationissimplified,andthenwewilllookatthetossinganddividingmethod.Sincegcd(a,b)=gcd(-a,b)Soweonlyneedtoconsiderthecasewhereaandbarebothpositiveintegers.
Theorem1.3.2(TheEuclideanAlgorithm)Assuminga,banda>b.Fromtheprincipleofdivision,weknowthatthereareh0,r0suchthat
a=bh0+r0,wherer0<b.
Ifr0>0,thereareh1,r1suchthat
b=r0h1+r1,where0r1<r0.
Ifr1>0,thereareh2,r2suchthat
r0=r1h2+r2,where0r2<r1.
Thiscontinuesuntilrn=0,ifn=0(ier0=0),thengcd(a,b)=b.Ifn1,thengcd(a,b)=rn-1.
Proof.Firstnoticethatifr00,becauser0>r1>r2>...isstrictlydecreasing,becauser0and0canonlyinsertatmostr0-1positiveinteger,Soweknowthattheremustbenr0suchthatrn=0.
Ifr0=0,thatis,a=bh0,soknowingthatbisafactorofa,itcanbeprovedthatbisthegreatestcommonfactorofa,b.Ifr0>0,itisknownfromLemma1.3.1
gcd(a,b)=gcd(b,r0)=gcd(r0,r1)=...=gcd(rn-1,rn)=gcd(rn-1,0)=rn-1.
Nowlet’slookatanexampleoffindingthegreatestcommonfactorbydividingbytossingandturning
Example1.3.3Wefindthegreatestcommonfactorofa=481andb=221.First,bytheprincipleofdivision,weget481=2.221+39,weknowthatr0=39.Soconsiderb=221dividedbyr0=39toget221=5.39+26,weknowthatr1=26,andthenr0=39isdividedbyr1=26gives39=1.26+13,knowingr2=13.Finally,becauser2=13dividesr1=26,weknowr3=0,sofromTheorem1.3.2weknowgcd(481,221)=r2=13.
Whenusingthetossandturnsdivisionmethodtofindthegreatestcommonfactor,youdon’treallyneedtofindrn=0.Forexample,intheaboveexample,itcanbeseenthatthegreatestcommonfactorofr0=39andr1=26is13.UsingLemma1.3.1,weknowthatgcd(a,b)=13.
Intheprevioussection,Corollary1.2.5toldusthatifgcd(a,b)=d,thenthereism,nsuchthatd=ma+nb.Atthattime,wedidnotmentionhowtofindthism,n,weusethetossanddividemethodtointroduceamethodtofindm,n,wecontinuetouseTheorem1.3.2notation,seer0=0,atthistimed=gcd(a,b)=bSoifm=0,n=1,thenwehaved=b=ma+nb.Whenr00butr1=0,weknowthatd=gcd(a,b)=r0.Therefore,usinga=bh0+r0,ifm=1,n=-h0,thend=r0=ma+nb.Similarly,ifr00,r10butr2=0,thend=gcd(a,b)=r1.Sousea=bh0+r0andb=r0h1+r1toknow
r1=b-r0h1=b-(a-bh0)h1=-h1a+(1+h0h1)b.
Euclideanalgorithm(2photos)
Soifm=-h1andn=1+h0h1,thend=r1=ma+nb.Accordingtothismethod,whenr0,r1andr2areallnon-zero,sinced=gcd(a,b)=rn-1rn-3=rn-2hn-1+rn-1weknowd=rn-3-hn-1rn-2.Usingthepreviousderivationmethod,weknowthattherearem1,m2,n1,n2suchthatrn-3=m1a+n1bandrn-2=m2a+n2b,sosubstituted=(m1a+n1b)-hn-1(m2a+n2b)=(m1-hn-1m2)a+(n1-hn-1n2)b.
Soifm=m1-hn-1m2andn=n1-hn-1n2,thend=ma+nb.
Theabovedescriptionseemslikewhenr00,foreachi{0,1,...,n-2}wemustfirstwriteriasri=mia+nib,andfinallyd=rn-1canbewrittenasma+nb.Infact,thisisjustaconvenienceforargumentation.Inactualoperation,weactuallywriteeachriasmi'ri-2+ni'Theformofri-1isslowlyreversedbacktod=ma+nb.Pleaseseethefollowingexample.
Example1.3.4WetrytousetheresultofExample1.3.3tofindm,nmakes13=gcd(481,221)=481m+221n.Firstwehave13=r2=39-26=r0-r1.Andr1=221-5.39=b-5r0,so13=r0-(b-5r0)=6r0-b.Fromr0=481-2.221=a-2b,weknowthat13=6(a-2b)-b=6a-13b.Som=6andn=-13willsatisfy13=481m+221n.
Itshouldbenotedthatthem,nfoundherewillnotbetheonlysetofsolutionsthatsatisfyd=ma+nb.Althoughtheabovedeductionprocessseemstohaveonlyonesetofsolutions,itcanonlybesaidtobetheaboveThemethodwillgetasetofsolutions,anditdoesnotguaranteethatallsolutionscanbefound.Forexample,ifm'=m+b,n'=n-a,thenm'a+n'b=(m+b)a+(n-a)b=ma+nb=d.Som',n'willalsobeanothersetofsolutions,sowhendiscussinguniquenessinthefuture,youmustnotsaythatitisderivedfromthepreviousonewithoutsufficientreason.Theprocessseesthattheonlyoneistheonlyone.Thegeneralpracticeistoassumethatyouhavetwosetsofsolutions,andthenusetheequationsthatthesetwosetsofsolutionsmeettofindtherelationshipbetweenthetwo.Let’slookatthefollowingpractices.
Proposition1.3.5Assumea,bandd=gcd(a,b).Ifx=m0,y=n0isasetofintegersolutionsofd=ax+by,thenforanyt,x=m0+bt/d,y=n0-at/disasetofd=ax+byIntegersolutions,andallintegersolutionsofd=ax+bymustbex=m0+bt/d,y=n0-at/dwheretissuchaform.
Proof.Assumethatx=m,y=nisasetofsolutionsofd=ax+by.Sinceithasbeenassumedthatx=m0,y=n0isalsoasetofsolutions,soam+bn=am0+bn0.Thatisa(m-m0)=b(n0-n).Sinced=gcd(a,b),wecanassumethata=a'd,b=b'dwherea',b'Andgcd(a',b')=1(seeCorollary1.2.3).Therefore,a'(m-m0)=b'(n0-n).Useb'|a'(m-m0),gcd(a',b')=1andProposition1.2.7⑴toobtainb'|m-m0.Inotherwords,thereistsuchthatm-m0=b't.Soweknowm=m0+b't=m0+bt/d.Substitutem=m0+bt/dbacktoam+bn=am0+bn0togetn=n0-at/d,sowecanprovethatd=ax+byTheintegersolutionsarex=m0+bt/d,y=n0-at/d,wheretisintheform.Finally,weonlyhavetoconfirmthatforanyt,x=m0+bt/d,y=n0-at/d.Isasetofintegersolutionsofd=ax+by,butsubstitutingx=m0+bt/d,y=n0-at/dintoax+bytoobtaina(m0+bt/d)+b(n0-at/d)=am0+bn0=d,sothistheoremisproved.
UsingProposition1.3.5wecanuseExample1.3.4tofindasetofintegersolutionsof13=481x+221yx=6,y=-13togetx=6+17t,y=-13-37twheretisalltheintegersolutionsof13=481x+221y.
Programdesign
Thefollowingpropertyisusedtodeterminethegreatestcommonfactoroftwopositiveintegersaandb:
⒈IfrisaTheremainderof÷b,andrisnot0,then
gcd(a,b)=gcd(b,r)
⒉thegreatestcommonfactorofaanditsmultipleisa.
Anotherwayofwritingis:
⒈Letrbetheremainderofa/b(0≤r
Ifr=0,thealgorithmends;bisIstheanswer.
⒉Exchange:seta←b,b←r,andreturntothefirststep.
Algorithmversion
Swiftlanguageversion
p>importFoundationfuncgcd(a:Int,b:Int)->Int{varx=a,y=bwhiley!=0{(x,y)=(y,x%y)}returnx}letx=75,y=100letresult=gcd(a:x,b:y)print("Thegreatestcommondivisorof\(x)and\(y)is\(result)")
Golanguageversion
packagemainimport"fmt"funcmain(){varx,yint=18,12result:=gcd(x,y)fmt.Printf("x,yThegreatestcommondivisoris:%d",result)}funcgcd(x,yint)int{fory!=0{x,y=y,x%yreturn>Pascallanguageversion
vara,b,c:integer;beginreadln(a,b);c:=amodb;whilec<>0dobegina:=b;b:=c;c:=amodb;end;write(b);end.Clanguageversion
/*EuropeJiLid'salgorithm:theprincipleofremainderandremainder:gcd(a,b)=gcd(b,amodb)Whenbis0,thegreatestcommondivisorofthetwonumbersisagetchar()andwillacceptthecarriagereturnofthepreviousscanfSymbol*/#includeunsignedintMaxCommonFactor(inta,intb){if(b<=0)returna;returnMaxCommonFactor(b,a%b);}unsignedintGcd(unsignedintM,unsignedintN){unsignedintRem;while(N>0)Rem=M%N;void(Mrem)M=N;intRem;intrem;,b;scanf("%d%d",&a,&b);printf("thegreatestcommonfactorof%dand%dis",a,b);printf("%d\n",Gcd(a,b));printf("recursion:%d\n",MaxCommonFactor(a,b));return0;}Rubylanguageversion
#CalculatethegreatestcommondivisorusingEuclideanalgorithm(typesettingomitted)defgcd(x,y)ify==0returnxelsereturngcd(y,x%y)endendC++version
#includeusingnamespacestd;intgcd(inta,intb){if(a%b==0)returnb;elsereturngcd(b,a%b);}intx,y;intmain(){cin>>x>>y;cout<<gcd(x,y);return0;}JavaEdition
intgcd(intm,intn){if(n==0){returnm;intr=m%n;returngcd(n,r);}JavaScriptversion
functiongcd(a,b){a,%b==0)returnb;returngcd(b,a%b);Pythonversion
defgcd(a,b):whilea!=0:a,b=b%a,areturnbErlangversion
gcd(A,0)->A;gcd(A,B)->gcd(B,AremB).RustEdition
pubfngcd(x:u64,y:u64)->u64{letremainder=x%y;ifremainder==0{returny;}else{returngcd(y,remainder);}}#[cfg(test)]modtests{usesuper::*;#[test]fngcd_works(){assert_eq!(gcd(2,4),2);assert_eq!(gcd(6,27),3);assert_eq!(gcd(4,_2),2);eq(gcd(27,6),3);}}Bashversion
functiongcd(){if[!-n"$2"];thenreturnfiif["$2"=="0"];thenecho"$1"returnfigcd"$2""$[$1%$2]"}ModuloPMultiplicativeinverseelement
Forintegersaandp,ifthereisanintegerbthatsatisfiesabmodp=1,itissaidthatbisthemodulopmultiplicativeinverseelementofa.
Theorem:Thenecessaryandsufficientconditionfortheexistenceofamultiplicativeinversemodulopisgcd(a,p)=1
Proof:
Firstprovethesufficiency
Ifgcd(a,p)=1,accordingtoEuler'stheorem,aφ(p)≡1modp,so
Obviouslyaφ(p)-1modpisthemodulopmultiplicativeinverseofa.
Provethenecessityagain
Assumingthatthemultiplicativeinverseofamodulopisb
ab≡1modp
p>thenab=kp+1,so1=ab-kp
Becausegcd(a,p)=d
sod|1
Sodcanonlybe1
Steinalgorithm
Euclideanalgorithmisatraditionalalgorithmforcalculatingthegreatestcommondivisoroftwonumbers,regardlessofBoththeoreticallyandefficiencyareverygood.Buthehasafatalflaw,thisflawwillonlyshowupwhenlargeprimenumbers.
Forhardwareplatforms,generallyintegersareupto64bits.Forsuchintegers,itisverysimpletocalculatethemodulusbetweentwonumbers.Forplatformswithawordlengthof32bits,itonlytakesoneinstructioncycletocalculatethemodulusoftwointegersthatdonotexceed32bits,anditonlytakesafewcyclestocalculatetheintegermodulusof64bitsorless.However,forlargerprimenumbers,suchacalculationprocesshastobedesignedbytheuser.Inordertocalculatethemodulusoftwointegersexceeding64bits,theusermayhavetoadoptatrialbusinessmethodsimilartothemanualcalculationprocessofmulti-digitdivision.Theprocessisnotonlycomplicated,butalsoconsumesalotofCPUtime.Formoderncryptographicalgorithms,therearemanysituationsthatrequirethecalculationofprimenumberswithmorethan128bits.Thedesignofsuchaprogramiseagertoabandondivisionandmodulus.
TheSteinalgorithmwasproposedbyJ.Steinin1961.Thismethodalsocalculatesthegreatestcommondivisoroftwonumbers.UnlikeEuclid'salgorithm,Stein'salgorithmonlyhasintegershiftandadditionandsubtraction,whichisaboonforprogrammers.
InordertoillustratethecorrectnessoftheSteinalgorithm,wemustfirstpayattentiontothefollowingconclusions:
gcd(a,a)=a,thatis,thecommondivisorofanumberanditsownisitsItself
gcd(ka,kb)=kgcd(a,b),thatis,thegreatestcommondivisoroperationandmultiplicationoperationcanbeexchanged,special,whenk=2,itmeanstwoevennumbersThegreatestcommondivisormustbedivisibleby2
C++/javaimplementation
//c++/javasteinalgorithm
intgcd(inta,intb)
{if(ab
{inttemp=a;a=b;b=temp;}
if(0==b)//thebasecase
returna;
if(a%2==0&&b%2==0)//aandbareeven
return2*gcd(a/2,b/2);
if(a%2==0)//onlyaiseven
returngcd(a/2,b);
if(b%2==0)//onlybiseven
returngcd(a,b/2);
returngcd((ab)/2,b);//aandbareodd
}
Algorithmextension
TheextendedEuclideanalgorithmcannotonlycalculatethegreatestcommondivisorof(a,b),butalsocalculatethemultiplicativeinverseelementofamodulobandbmoda,whichisdescribedinClanguageasfollows:
#includeunsignedintgcdExtended(inta,intb,int*x,int*y);intmain(void){inta,b,GCD;intx,y;a=1232,b=cd,573;1232,b=cd,573;573),x=20andy=-431232x+573y=124640-24639=1orgcdExtended(573,1232),x=-43,y=20+1573x+1232y=1-43*573*573**20=-24639+57640=1gcdExtended(9151,5787)Whenx=2011,y=-3180*/GCD=gcdExtended(a,b,&x,&y);printf("gcdExtended(%d,%d)x=%d,=%d,y=%d\n",a,b,GCD,x,y);return0;}//ClanguageimplementationofEuclid'sextendedalgorithm//ax+by=1unsignedintgcdExtended(inta,intb,int*x,int*y){if(a==0){*x=0;*y=1;returnb;cd=cd,intb,cd,intg,intx1,y1;a,&x1,&y1);*x=y1-(b/a)*x1;*y=x1;returngcd;}ExtendedEuclideanalgorithmforthegreatestcommondivisorThecalculationofisconsistentwiththeordinaryEuclideanalgorithm.Calculatingthemultiplicativeinverseisdifficulttounderstand.IthoughtforhalfanhourbeforeIcameupwithawaytoprovehim.
Firstrepeatoneoftheargumentsintheclumsydivision:
Ifgcd(a,b)=d,thentherearem,n,sothatd=ma+nb,callthisrelationshipa,bcombinedintegerd,m,narecalledcombinationcoefficients.Whend=1,thereisma+nb=1.Atthistime,itcanbeseenthatmisthemultiplicativeinverseelementofamodulob,andnisthemultiplicativeinverseelementofbmoduloa.
Inordertoprovetheaboveconclusion,weregardxiandyiintheabovecalculationastheinitialiterativevalueofti,examineasetofnumbers(t1,t2,t3),anduseinductiontoprove:AfterthecalculationoftheJilitalgorithm,eachrowsatisfiesa×t1+b×t2=t3
Thefirstrow:1×a+0×b=aisestablished
ThesecondRow:0×a+1×b=bholds
Assumingthatthefirstkrowsarealltrue,examinethek+1throw
Fork-1rowandkrow
p>t1(k-1)t2(k-1)t3(k-1)
t1(k)t2(k)t3(k)
RespectivelySatisfies:
t1(k-1)×a+t2(k-1)×b=t3(k-1)
t1(k)×a+t2(k)×b=t3(k)
AccordingtotheextendedEuclideanalgorithm,assumingt3(k-1)=jt3(k)+r
then:
t3(k+1)=r
t2(k+1)=t2(k-1)-j×t2(k)
t1(k+1)=t1(k-1)-j×t1(k)
then
t1(k+1)×a+t2(k+1)×b
=t1(k-1)×a-j×t1(k)×a+
t2(k-1)×b-j×t2(k)×b
p>=t3(k-1)-jt3(k)=r
=t3(k+1)
Certified
Therefore,whenthefinalt3isiterativelycalculatedto1,thereist1×a+t2×b=1.Obviously,t1isthemultiplicativeinverseelementofamodulob,andt2isthemultiplicativeinverseelementofbmoduloa.