C++. // C++ program to find GCD of two numbers. #include . using namespace std;. int static dp[1001][1001]; ; Java. // Java ...
Skiptocontent
TutorialsPracticeDS&Algo.MustDoQuestionsDSATopic-wiseDSACompany-wiseAlgorithmsAnalysisofAlgorithmsAsymptoticAnalysisWorst,AverageandBestCasesAsymptoticNotationsLittleoandlittleomeganotationsLowerandUpperBoundTheoryAnalysisofLoopsSolvingRecurrencesAmortizedAnalysisWhatdoes'SpaceComplexity'mean?Pseudo-polynomialAlgorithmsPolynomialTimeApproximationSchemeATimeComplexityQuestionSearchingAlgorithmsSortingAlgorithmsGraphAlgorithmsPatternSearchingGeometricAlgorithmsMathematicalBitwiseAlgorithmsRandomizedAlgorithmsGreedyAlgorithmsDynamicProgrammingDivideandConquerBacktrackingBranchandBoundAllAlgorithmsDataStructuresArraysLinkedListStackQueueBinaryTreeBinarySearchTreeHeapHashingGraphAdvancedDataStructureMatrixStringsAllDataStructuresInterviewCornerCompanyPreparationTopTopicsPracticeCompanyQuestionsInterviewExperiencesExperiencedInterviewsInternshipInterviewsCompetititveProgrammingDesignPatternsSystemDesignTutorialMultipleChoiceQuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGoLanguageHTMLCSSKotlinCSSubjectsMathematicsOperatingSystemDBMSComputerNetworksComputerOrganizationandArchitectureTheoryofComputationCompilerDesignDigitalLogicSoftwareEngineeringGATEGATEComputerScienceNotesLastMinuteNotesGATECSSolvedPapersGATECSOriginalPapersandOfficialKeysGATE2021DatesGATECS2021SyllabusImportantTopicsforGATECSWebTechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftwareDesignsSoftwareDesignPatternsSystemDesignTutorialSchoolLearningSchoolProgrammingMathematicsNumberSystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMathsNotes(Class8-12)Class8NotesClass9NotesClass10NotesClass11NotesClass12NotesNCERTSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionRDSharmaSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionPhysicsNotes(Class8-11)Class8NotesClass9NotesClass10NotesClass11NotesISROCSISROCSSolvedPapersISROCSOriginalPapersandOfficialKeysISROCSSyllabusforScientist/EngineerExamUGCNETCSUGCNETCSNotesPaperIIUGCNETCSNotesPaperIIIUGCNETCSSolvedPapersStudentCampusAmbassadorProgramSchoolAmbassadorProgramProjectGeekoftheMonthCampusGeekoftheMonthPlacementCourseCompetititveProgrammingTestimonialsGeekontheTopCareersInternshipJobsApplyforJobsPostaJobCourses
ComewritearticlesforusandgetfeaturedLearnandcodewiththebestindustryexpertsGetaccesstoad-freecontent,doubtassistanceandmore!ComeandfindyourdreamjobwithusGeeksDigestQuizzesGeeksCampusGblogArticlesIDECampusMantri
HomeSavedVideosCoursesGBlogPuzzlesWhat'sNew?
ChangeLanguage
DataStructuresAlgorithmsInterviewPreparationTopic-wisePracticeC++JavaPythonCompetitiveProgrammingMachineLearningWebDevelopmentPuzzlesProjectIdeasGFGSchool
RelatedArticles
▲RelatedArticlesWriteaniterativeO(Logy)functionforpow(x,y)Writeaprogramtocalculatepow(x,n)ModularExponentiation(PowerinModularArithmetic)Modularexponentiation(Recursive)ModularmultiplicativeinverseEuclideanalgorithms(BasicandExtended)ProgramtofindGCDorHCFoftwonumbersProgramtofindLCMoftwonumbersLCMofgivenarrayelementsFindingLCMofmorethantwo(orarray)numberswithoutusingGCDGCDofmorethantwo(orarray)numbersSieveofEratosthenesSieveofEratosthenesin0(n)timecomplexityHowisthetimecomplexityofSieveofEratosthenesisn*log(log(n))?SegmentedSieveSegmentedSieve(PrintPrimesinaRange)PrimeFactorizationusingSieveO(logn)formultiplequeriesEfficientprogramtoprintallprimefactorsofagivennumberPrimeFactorPollard’sRhoAlgorithmforPrimeFactorizationProgramforFibonaccinumbersWriteaprogramtoprintallpermutationsofagivenstringSetinC++StandardTemplateLibrary(STL)C++DataTypesCoinChange|DP-7CountingSortProgramforDecimaltoBinaryConversionPrimeNumbersTableofContentsWriteaniterativeO(Logy)functionforpow(x,y)Writeaprogramtocalculatepow(x,n)ModularExponentiation(PowerinModularArithmetic)Modularexponentiation(Recursive)ModularmultiplicativeinverseEuclideanalgorithms(BasicandExtended)ProgramtofindGCDorHCFoftwonumbersProgramtofindLCMoftwonumbersLCMofgivenarrayelementsFindingLCMofmorethantwo(orarray)numberswithoutusingGCDGCDofmorethantwo(orarray)numbersSieveofEratosthenesSieveofEratosthenesin0(n)timecomplexityHowisthetimecomplexityofSieveofEratosthenesisn*log(log(n))?SegmentedSieveSegmentedSieve(PrintPrimesinaRange)PrimeFactorizationusingSieveO(logn)formultiplequeriesEfficientprogramtoprintallprimefactorsofagivennumberPrimeFactorPollard’sRhoAlgorithmforPrimeFactorizationProgramforFibonaccinumbersWriteaprogramtoprintallpermutationsofagivenstringSetinC++StandardTemplateLibrary(STL)C++DataTypesCoinChange|DP-7CountingSortProgramforDecimaltoBinaryConversionPrimeNumbersImproveArticle
SaveArticle
LikeArticle
ProgramtofindGCDorHCFoftwonumbersDifficultyLevel:
EasyLastUpdated:
20Dec,2021GCD(GreatestCommonDivisor)orHCF(HighestCommonFactor)oftwonumbersisthelargestnumberthatdividesbothofthem. Hey!Lookingforsomegreatresourcessuitableforyoungones?You'vecometotherightplace.Checkoutourself-pacedcoursesdesignedforstudentsofgradesI-XII. StartwithtopicslikePython,HTML,ML,andlearntomakesomegamesandappsallwiththehelpofourexpertlydesignedcontent!Sostudentsworrynomore,becauseGeeksforGeeksSchoolisnowhere! ForexampleGCDof20and28is4andGCDof98and56is14.Forsolution supposea=98&b=56 a>bsoputa=a-bandbis remainsame so a=98-56=42 &b=56.Nowb>a so b=b-aand aissame b=56-42=14&a=42 .42is 3timesof14 soHCFis14 .likewise a=36 &b=60 ,hereb>a sob=24&a=36 nowa>bsoa=12&b=24 .12isHCFof36and60. This concept is always satisfying. Recommended:Pleasesolveiton“PRACTICE”first,beforemovingontothesolution. Asimplesolutionistofindallprimefactorsofbothnumbers,thenfindintersectionofallfactorspresentinbothnumbers.Finallyreturnproductofelementsintheintersection.AnefficientsolutionistouseEuclideanalgorithmwhichisthemainalgorithmusedforthispurpose.Theideais,GCDoftwonumbersdoesn’tchangeifsmallernumberissubtractedfromabiggernumber. C++//C++programtofindGCDoftwonumbers#includeusingnamespacestd;//Recursivefunctiontoreturngcdofaandbintgcd(inta,intb){ //Everythingdivides0 if(a==0) returnb; if(b==0) returna; //basecase if(a==b) returna; //aisgreater if(a>b) returngcd(a-b,b); returngcd(a,b-a);} //Driverprogramtotestabovefunctionintmain(){ inta=98,b=56; cout< //Recursivefunctiontoreturngcdofaandbintgcd(inta,intb){ //Everythingdivides0 if(a==0) returnb; if(b==0) returna; //basecase if(a==b) returna; //aisgreater if(a>b) returngcd(a-b,b); returngcd(a,b-a);} //Driverprogramtotestabovefunctionintmain(){ inta=98,b=56; printf("GCDof%dand%dis%d",a,b,gcd(a,b)); return0;}Java//JavaprogramtofindGCDoftwonumbersclassTest{ //Recursivefunctiontoreturngcdofaandb staticintgcd(inta,intb) { //Everythingdivides0 if(a==0) returnb; if(b==0) returna; //basecase if(a==b) returna; //aisgreater if(a>b) returngcd(a-b,b); returngcd(a,b-a); } //Drivermethod publicstaticvoidmain(String[]args) { inta=98,b=56; System.out.println("GCDof"+a+"and"+b+"is"+gcd(a,b)); }}Python3#Recursivefunctiontoreturngcdofaandbdefgcd(a,b): #Everythingdivides0 if(a==0): returnb if(b==0): returna #basecase if(a==b): returna #aisgreater if(a>b): returngcd(a-b,b) returngcd(a,b-a) #Driverprogramtotestabovefunctiona=98b=56if(gcd(a,b)): print('GCDof',a,'and',b,'is',gcd(a,b))else: print('notfound') #ThiscodeiscontributedbyDanishRazaC#//C#programtofindGCDoftwo//numbersusingSystem; classGFG{ //Recursivefunctiontoreturn //gcdofaandb staticintgcd(inta,intb) { //Everythingdivides0 if(a==0) returnb; if(b==0) returna; //basecase if(a==b) returna; //aisgreater if(a>b) returngcd(a-b,b); returngcd(a,b-a); } //Drivermethod publicstaticvoidMain() { inta=98,b=56; Console.WriteLine("GCDof" +a+"and"+b+"is" +gcd(a,b)); }} //Thiscodeiscontributedbyanuj_67.PHP$b) returngcd($a-$b,$b); returngcd($a,$b-$a);} //Drivercode$a=98;$b=56; echo"GCDof$aand$bis",gcd($a,$b); //ThiscodeiscontributedbyAniveshTiwari?>JavascriptOutput: GCDof98and56is14DynamicProgrammingApproach(TopDownUsingMemoization):C++//C++programtofindGCDoftwonumbers#includeusingnamespacestd; intstaticdp[1001][1001]; //Functiontoreturngcdofaandbintgcd(inta,intb){ //Everythingdivides0 if(a==0) returnb; if(b==0) returna; //basecase if(a==b) returna; //ifavalueisalready //presentindp if(dp[a][b]!=-1) returndp[a][b]; //aisgreater if(a>b) dp[a][b]=gcd(a-b,b); //bisgreater else dp[a][b]=gcd(a,b-a); //returndp returndp[a][b];} //Driverprogramtotestabovefunctionintmain(){ inta=98,b=56; memset(dp,-1,sizeof(dp)); cout<b) dp[a][b]=gcd(a-b,b); //bisgreater else dp[a][b]=gcd(a,b-a); //returndp returndp[a][b]; } //Drivermethod publicstaticvoidmain(String[]args) { for(inti=0;i<1001;i++){ for(intj=0;j<1001;j++){ dp[i][j]=-1; } } inta=98,b=56; System.out.println("GCDof"+a+"and"+b+"is"+gcd(a,b)); }} //ThiscodeiscontributedbySamimHossainMondal.Python#functiontoreturngcdofaandb #Takingthematrixasgloballydp=[[-1foriinrange(1001)]forjinrange(1001)] defgcd(a,b): #Everythingdivides0 if(a==0): returnb if(b==0): returna #basecase if(a==b): returna if(dp[a][b]!=-1): returndp[a][b] #aisgreater if(a>b): dp[a][b]=gcd(a-b,b) else: dp[a][b]=gcd(a,b-a) returndp[a][b] #Driverprogramtotestabovefunctiona=98b=56if(gcd(a,b)): print('GCDof',a,'and',b,'is',gcd(a,b))else: print('notfound') #ThiscodeiscontributedbySamimHossainMondal.C#//C#programtofindGCDoftwonumbersusingSystem;classGFG{ staticint[,]dp=newint[1001,1001]; //Recursivefunctiontoreturngcdofaandb staticintgcd(inta,intb) { //Everythingdivides0 if(a==0) returnb; if(b==0) returna; //basecase if(a==b) returna; //ifavalueisalready //presentindp if(dp[a,b]!=-1) returndp[a,b]; //aisgreater if(a>b) dp[a,b]=gcd(a-b,b); //bisgreater else dp[a,b]=gcd(a,b-a); //returndp returndp[a,b]; } //Drivermethod publicstaticvoidMain() { for(inti=0;i<1001;i++){ for(intj=0;j<1001;j++){ dp[i,j]=-1; } } inta=98,b=56; Console.Write("GCDof"+a+"and"+b+"is"+gcd(a,b)); }} //ThiscodeiscontributedbySamimHossainMondal.Javascript//OutputGCDof98and56is14TimeComplexity:O(a*b)AuxiliarySpace:O(1)AmoreefficientsolutionistousemodulooperatorinEuclideanalgorithm. C++//C++programtofindGCDoftwonumbers#includeusingnamespacestd;//Recursivefunctiontoreturngcdofaandbintgcd(inta,intb){ if(b==0) returna; returngcd(b,a%b); } //Driverprogramtotestabovefunctionintmain(){ inta=98,b=56; cout< //Recursivefunctiontoreturngcdofaandbintgcd(inta,intb){ if(b==0) returna; returngcd(b,a%b);} //Driverprogramtotestabovefunctionintmain(){ inta=98,b=56; printf("GCDof%dand%dis%d",a,b,gcd(a,b)); return0;}Java//JavaprogramtofindGCDoftwonumbersclassTest{ //Recursivefunctiontoreturngcdofaandb staticintgcd(inta,intb) { if(b==0) returna; returngcd(b,a%b); } //Drivermethod publicstaticvoidmain(String[]args) { inta=98,b=56; System.out.println("GCDof"+a+"and"+b+"is"+gcd(a,b)); }}Python3#Recursivefunctiontoreturngcdofaandbdefgcd(a,b): #Everythingdivides0 if(b==0): returna returngcd(b,a%b) #Driverprogramtotestabovefunctiona=98b=56if(gcd(a,b)): print('GCDof',a,'and',b,'is',gcd(a,b))else: print('notfound') #ThiscodeiscontributedbyDanishRazaC#//C#programtofindGCDoftwo//numbersusingSystem; classGFG{ //Recursivefunctiontoreturn //gcdofaandb staticintgcd(inta,intb) { if(b==0) returna; returngcd(b,a%b); } //Drivermethod publicstaticvoidMain() { inta=98,b=56; Console.WriteLine("GCDof" +a+"and"+b+"is" +gcd(a,b)); }} //Thiscodeiscontributedbyanuj_67.PHPJavascriptOutput: GCDof98and56is14ThetimecomplexityfortheabovealgorithmisO(log(max(a,b)))thederivationforthisisobtainedfromtheanalysisoftheworst-casescenario.Whatwedoisweaskwhatarethe2leastnumbersthattake1step,thosewouldbe(1,1).Ifwewanttoincreasethenumberofstepsto2whilekeepingthenumbersaslowaspossibleaswecantakethenumberstobe(1,2).Similarly,for3steps,thenumberswouldbe(2,3),4wouldbe(3,5),5wouldbe(5,8).Sowecannoticeapatternhere,forthenthstepthenumberswouldbe(fib(n),fib(n+1)). Sotheworst-casetimecomplexitywouldbeO(n)wherea>=fib(n)andb>=fib(n+1). NowFibonacciseriesisanexponentiallygrowingserieswheretheratioofnth/(n-1)thtermapproaches(sqrt(5)-1)/2whichisalsocalledthegoldenratio.Sowecanseethatthetimecomplexityofthealgorithmincreaseslinearlyasthetermsgrowexponentiallyhencethetimecomplexitywouldbelog(max(a,b)).PleasereferGCDofmorethantwo(orarray)numberstofindHCFofmorethantwonumbers.Pleasewritecommentsifyoufindanythingincorrect,oryouwanttosharemoreinformationaboutthetopicdiscussedaboveMyPersonalNotes
arrow_drop_upSave
LikePreviousEuclideanalgorithms(BasicandExtended)Next
ProgramtofindLCMoftwonumbersRecommendedArticlesPage:17,Sep1812,Apr1922,Aug1824,Dec1731,Jan1824,Nov1807,Dec2123,Nov2024,Nov1820,Sep1925,Mar2013,Jan2116,Sep2020,Oct2027,Mar1727,Mar1721,Nov1823,Dec2129,Oct1719,Jun1816,Aug1615,Jan1718,Apr1711,Nov17ArticleContributedBy:GeeksforGeeksVotefordifficultyCurrentdifficulty:
EasyEasy
Normal
Medium
Hard
ExpertImprovedBy:vt_mSoumikMondalSidhantAgarwal1ankitjhunjhunwalamayanktyagi1709_saurabh_jaiswalsukhsoni803samim2000ArticleTags:GCD-LCMSAPLabsMathematicalSchoolProgrammingPracticeTags:SAPLabsMathematicalReportIssueWritingcodeincomment?
Pleaseuseide.geeksforgeeks.org,
generatelinkandsharethelinkhere.
LoadCommentsWhat'sNewViewDetailsViewDetailsViewDetailsMostpopularinMathematicalOperatorsinC/C++ProgramtofindsumofelementsinagivenarrayProgramforfactorialofanumberMergetwosortedarraysWriteaprogramtoreversedigitsofanumberMostvisitedinSchoolProgrammingPythonDictionaryArraysinC/C++InheritanceinC++ReverseastringinJavaC++ClassesandObjects×
Weusecookiestoensureyouhavethebestbrowsingexperienceonourwebsite.Byusingoursite,you
acknowledgethatyouhavereadandunderstoodour
CookiePolicy&
PrivacyPolicy
GotIt!
StartYourCodingJourneyNow!Login
Register