GCD function in c++ sans cmath library - Stack Overflow

文章推薦指數: 80 %
投票人數:10人

The libstdc++ algorithm library has a hidden gcd function (I'm using g++ 4.6.3). #include #include int main() { cout ... Home Public Questions Tags Users Collectives ExploreCollectives FindaJob Jobs Companies Teams StackOverflowforTeams –Collaborateandshareknowledgewithaprivategroup. CreateafreeTeam WhatisTeams? Teams CreatefreeTeam CollectivesonStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. Learnmore Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. Learnmore GCDfunctioninc++sanscmathlibrary AskQuestion Asked 9years,6monthsago Active 4monthsago Viewed 80ktimes 25 9 I'mwritingamixednumeralclassandneedaquickandeasy'greatestcommondivisor'function.Cananyonegivemethecodeoralinktothecode? c++greatest-common-divisor Share Follow editedAug15'14at23:47 ConnorBlack askedJun8'12at22:04 ConnorBlackConnorBlack 6,4411212goldbadges3535silverbadges6868bronzebadges 1 1 Thereareabunchoffunoneshere:codegolf.stackexchange.com/questions/35587 – technosaurus Aug15'14at18:41 Addacomment  |  5Answers 5 Active Oldest Votes 57 Thelibstdc++algorithmlibraryhasahiddengcdfunction(I'musingg++4.6.3). #include #include intmain() { cout<<:__gcd return0 youarewelcome: update:as>header. Share Follow editedJul1'17at15:10 answeredDec18'13at17:05 TomaszPosłusznyTomaszPosłuszny 98799silverbadges1414bronzebadges 4 21 Youshouldn'trelyonundocumentedfeatureslikethatastheycanchangebetweenlibraryreleases. – vmrob Jan21'14at19:06 IsitavailableforMSVC? – NaseefChowdhury Mar21'14at18:51 2 @vmrob:Agreed.YoucanalwayscopyimplementationfromSTL.Mbt925:Done. – TomaszPosłuszny Mar30'14at15:38 1 thatsmellslikecheating;) – moldovean May15'15at17:58 Addacomment  |  43 I'mtemptedtovotetoclose--itseemsdifficulttobelievethatanimplementationwouldbehardtofind,butwhoknowsforsure. template NumberGCD(Numberu,Numberv){ while(v!=0){ Numberr=u%v; u=v; v=r; } returnu; } InC++17ornewer,youcanjust#include,andusestd::gcd(andifyoucareaboutthegcd,chancesareprettyfairthatyou'llbeinterestedinthestd::lcmthatwasaddedaswell). Share Follow editedAug30at21:37 answeredJun8'12at22:10 JerryCoffinJerryCoffin 447k7474goldbadges585585silverbadges10491049bronzebadges 2 2 Thanks.AndIgoogledforagood20minuteanddidn'tyieldanyclearresults. – ConnorBlack Jun8'12at22:14 1 @JerryCoffin:Whynotjusttemplatethis? – einpoklum May24'16at8:13 Addacomment  |  19 Aquickrecursiveversion: unsignedintgcd(unsignedintn1,unsignedintn2){ return(n2==0)?n1:gcd(n2,n1%n2); } ortheequivalentiterativeversionifyou'reviolentlyopposedtorecursion(a): unsignedintgcd(unsignedintn1,unsignedintn2){ unsignedinttmp; while(n2!=0){ tmp=n1; n1=n2; n2=tmp%n2; } returnn1; } Justsubstituteinyourowndatatype,zerocomparison,assignmentandmodulusmethod(ifyou'reusingsomenon-basictypelikeabignumclass,forexample). ThisfunctionactuallycamefromanearlieranswerofmineforworkingoutintegralaspectratiosforscreensizesbuttheoriginalsourcewastheEuclideanalgorithmIlearntalongtimeago,detailedhereonWikipediaifyouwanttoknowthemathbehindit. (a)Theproblemwithsomerecursivesolutionsisthattheyapproachtheanswersoslowlyyoutendtorunoutofstackspacebeforeyougetthere,suchaswiththeverybadlythoughtout(pseudo-code): defsum(a:unsigned,b:unsigned): ifb==0:returna returnsum(a+1,b-1) You'llfindthatveryexpensiveonsomethinglikesum(1,1000000000)asyou(tryto)useupabillionorsostackframes.Theidealusecaseforrecursionissomethinglikeabinarysearchwhereyoureducethesolutionspacebyhalfforeachiteration.Thegreatestcommondivisorisalsoonewherethesolutionspacereducesrapidlysofearsaboutmassivestackuseareunfoundedthere. Share Follow editedMay23'17at12:02 CommunityBot 111silverbadge answeredJun8'12at22:13 paxdiablopaxdiablo 798k218218goldbadges15121512silverbadges18731873bronzebadges 3 1 +1Youcanevenaddtemplatetoreplacetheint,addaconstexprkeywordbeforethefunctionandyouhaveanicecompile-time/runtimegenericfunction. – authchir Jun9'12at3:36 Possibletypoinyoursecondmethod.Shoulditreturnn1?n2willbydefinitionalwaysbezeroatthatpoint. – JimBlackler Jan16'14at0:37 Goodcatch,@Jim,fixedthatup. – paxdiablo Jan16'14at0:50 Addacomment  |  8 ForC++17youcanusestd::gcddefinedinheader: autores=std::gcd(10,20); Share Follow answeredApr28'17at23:54 chema989chema989 3,46322goldbadges1717silverbadges3232bronzebadges Addacomment  |  6 TheEuclideanalgorithmisquiteeasytowriteinC. intgcd(inta,intb){ while(b!=0){ intt=b; b=a%b; a=t; } returna; } Share Follow answeredJun8'12at22:16 DavidNehmeDavidNehme 21k88goldbadges7575silverbadges114114bronzebadges Addacomment  |  YourAnswer ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers. Draftsaved Draftdiscarded Signuporlogin SignupusingGoogle SignupusingFacebook SignupusingEmailandPassword Submit Postasaguest Name Email Required,butnevershown PostYourAnswer Discard Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy Nottheansweryou'relookingfor?Browseotherquestionstaggedc++greatest-common-divisororaskyourownquestion. TheOverflowBlog Ifollowedmydreamsandgotdemotedtosoftwaredeveloper HowoftendopeopleactuallycopyandpastefromStackOverflow?Nowweknow. FeaturedonMeta ProvidingaJavaScriptAPIforuserscripts Congratulationstothe59sitesthatjustleftBeta Linked 95 What'sthealgorithmtocalculateaspectratio? 4 c++GreatestCommonDivisor -2 GCDfunctionsyntaxinC++ -3 Relativeprimenumbers Related 630 StoringC++templatefunctiondefinitionsina.CPPfile 1260 WhereandwhydoIhavetoputthe"template"and"typename"keywords? 3034 Whyis"usingnamespacestd;"consideredbadpractice? 1506 WhydoweneedvirtualfunctionsinC++? 71 HowtofindGCD,LCMonasetofnumbers 1117 Canalocalvariable'smemorybeaccessedoutsideitsscope? 1788 ImageProcessing:AlgorithmImprovementfor'Coca-ColaCan'Recognition 648 Arethedaysofpassingconststd::string&asaparameterover? 1544 Replacinga32-bitloopcounterwith64-bitintroducescrazyperformancedeviationswith_mm_popcnt_u64onIntelCPUs HotNetworkQuestions SpeedupDoloopsinMMA13.0 HowcanIgetaslicefromanOptioninRust? Functiontomakealistasunsortedaspossible Canasmallemployeraskmeaboutmedicalconditionsbeforehiringme? Python-Tkinter-periodictableofchemicalelements Woulditbefeasibletodecelerateacrewedvehiclefrom~25km/sonlyusingtheatmosphereofMars(inthecontextofan"expresstransit")? HowcanIscalecolorbarandmakeitconsistentwithcolorofplot HowcanIget...justalittlebithigher? whichcomes1st-DomainexpertiseorExperimentalapproach UsingaPCBtraceasaheater/HilbertCurves John3:16"...onlybegottenson...","...onlyson..."whichismoreauthenticandreliable? Whosaid,"Theonlywaytomodelaninfinitelycomplexsystemiswiththesystem,itself"? Gen.1:20isreptileablative? H-bridgerequirements What’sawordorphrasethatmeans“toreduceambiguity”? Whylandsupplyisinelastic? Dotherefereesseetheprofileofauthors? Theoremsthatareessentiallyimpossibletoguessbyempiricalobservation Whydosomecountrieshavemorethanonestockexchange? Whatwouldittakeforaircrafttofullyreplacenavalvessels? Whatcountsasfullcoverforaseekingarrow? Howdoesariverfreezewhenthewaterkeepsmoving? Unpublishedchangestotravelrules Ispottedapaperwhichhassixpagesworthofplagiarism:shouldIreportittotheeditorofthejournal? morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-cpp Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?