Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Practice Mathematical Algorithm
  • Mathematical Algorithms
  • Pythagorean Triplet
  • Fibonacci Number
  • Euclidean Algorithm
  • LCM of Array
  • GCD of Array
  • Binomial Coefficient
  • Catalan Numbers
  • Sieve of Eratosthenes
  • Euler Totient Function
  • Modular Exponentiation
  • Modular Multiplicative Inverse
  • Stein's Algorithm
  • Juggler Sequence
  • Chinese Remainder Theorem
  • Quiz on Fibonacci Numbers
Open In App
Next Article:
Check if two numbers are co-prime or not
Next article icon

Program to Find GCD or HCF of Two Numbers

Last Updated : 21 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given two positive integers a and b, the task is to find the GCD of the two numbers.

Note: The GCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two numbers is the largest number that divides both of them. 

gcd

Examples:

Input: a = 20, b = 28
Output: 4
Explanation: The factors of 20 are 1, 2, 4, 5, 10 and 20. The factors of 28 are 1, 2, 4, 7, 14 and 28. Among these factors, 1, 2 and 4 are the common factors of both 20 and 28. The greatest among the common factors is 4.

Input: a = 60, b = 36
Output: 12
Explanation: GCD of 60 and 36 is 12.

Table of Content

  • [Approach - 1] Using Loop - O(min(a, b)) Time and O(1) Space
  • [Approach - 2] Euclidean Algorithm using Subtraction - O(min(a,b)) Time and O(min(a,b)) Space
  • [Approach - 3 ] Modified Euclidean Algorithm using Subtraction by Checking Divisibility - O(min(a, b)) Time and O(min(a, b)) Space
  • [Approach - 4] Optimized Euclidean Algorithm by Checking Remainder
  • [Approach - 5] Using Built-in Function - O(log(min(a, b))) Time and O(1) Space

[Approach - 1] Using Loop - O(min(a, b)) Time and O(1) Space

The idea is to find the minimum of the two numbers and find its highest factor which is also a factor of the other number.

C++
#include <iostream> using namespace std;  int gcd(int a, int b) {     // Find Minimum of a and b     int result = min(a, b);     while (result > 0) {         if (a % result == 0 && b % result == 0) {             break;         }         result--;     }      // Return gcd of a and b     return result; }  int main() {     int a = 20, b = 28;     cout << gcd(a, b);     return 0; } 
Java
import java.io.*;  class GFG {      static int gcd(int a, int b)     {         // Find Minimum of a and b         int result = Math.min(a, b);         while (result > 0) {             if (a % result == 0 && b % result == 0) {                 break;             }             result--;         }          // Return gcd of a and b         return result;     }      public static void main(String[] args)     {         int a = 20, b = 28;         System.out.print(gcd(a, b));     } } 
Python
def gcd(a, b):      # Find Minimum of a and b     result = min(a, b)      while result > 0:         if a % result == 0 and b % result == 0:             break         result -= 1      # Return gcd of a and b     return result   if __name__ == '__main__':     a = 20     b = 28     print(gcd(a, b)) 
C#
using System;  class GFG {          // Function to find gcd of two numbers     static int gcd(int a, int b) {         // Find Minimum of a and b         int result = Math.Min(a, b);          while (result > 0)         {             if (a % result == 0 && b % result == 0)                 break;             result--;         }          // Return gcd of a and b         return result;     }      static void Main()     {         int a = 20;         int b = 28;         Console.WriteLine(gcd(a, b));     } } 
JavaScript
function gcd(a, b) {      // Find Minimum of a and b     let result = Math.min(a, b);      while (result > 0) {         if (a % result === 0 && b % result === 0) {             break;         }         result--;     }      // Return gcd of a and b     return result; }  // Driver Code let a = 20; let b = 28; console.log(gcd(a, b)); 

Output
4

Below both approaches are optimized approaches of the above code.

[Approach - 2] Euclidean Algorithm using Subtraction - O(min(a,b)) Time and O(min(a,b)) Space

The idea of this algorithm is, the GCD of two numbers doesn't change if the smaller number is subtracted from the bigger number. This is the Euclidean algorithm by subtraction. It is a process of repeat subtraction, carrying the result forward each time until the result is equal to any one number being subtracted.

Pseudo-code:

gcd(a, b):
    if a = b:
        return a
    if a > b:
        return gcd(a - b, b)
    else:
        return gcd(a, b - a)

C++
#include <iostream> using namespace std;  int gcd(int a, int b) {     // Everything divides 0     if (a == 0)         return b;     if (b == 0)         return a;      // Base case     if (a == b)         return a;      // a is greater     if (a > b)         return gcd(a - b, b);     return gcd(a, b - a); }  int main() {     int a = 20, b = 28;     cout << gcd(a, b);     return 0; } 
Java
class GfG {      static int gcd(int a, int b) {         // Everything divides 0         if (a == 0)             return b;         if (b == 0)             return a;          // Base case         if (a == b)             return a;          // a is greater         if (a > b)             return gcd(a - b, b);         return gcd(a, b - a);     }      public static void main(String[] args) {         int a = 20, b = 28;         System.out.println(gcd(a, b));     } } 
Python
def gcd(a, b):        # Everything divides 0     if a == 0:         return b     if b == 0:         return a      # Base case     if a == b:         return a      # a is greater     if a > b:         return gcd(a - b, b)     return gcd(a, b - a)  if __name__ == '__main__':     a = 20     b = 28     print(gcd(a, b)) 
C#
using System;  class GfG {     static int gcd(int a, int b) {         // Everything divides 0         if (a == 0)             return b;         if (b == 0)             return a;          // Base case         if (a == b)             return a;          // a is greater         if (a > b)             return gcd(a - b, b);         return gcd(a, b - a);     }      static void Main()     {         int a = 20, b = 28;         Console.WriteLine(gcd(a, b));     } } 
JavaScript
function gcd(a, b) {     // Everything divides 0     if (a === 0)         return b;     if (b === 0)         return a;      // Base case     if (a === b)         return a;      // a is greater     if (a > b)         return gcd(a - b, b);     return gcd(a, b - a); }  // Driver code let a = 20, b = 28; console.log(gcd(a, b)); 

Output
4

[Approach - 3 ] Modified Euclidean Algorithm using Subtraction by Checking Divisibility - O(min(a, b)) Time and O(min(a, b)) Space

The above method can be optimized based on the following idea:

If we notice the previous approach, we can see at some point, one number becomes a factor of the other so instead of repeatedly subtracting till both become equal, we can check if it is a factor of the other.

Illustration:

See the below illustration for a better understanding:

Consider a = 98 and b = 56

a = 98, b = 56:

  • a > b so put a = a-b and b remains same. So  a = 98-56 = 42  & b= 56. 

a = 42, b = 56:

  • Since b > a, we check if b%a=0. Since answer is no, we proceed further. 
  • Now b>a. So b = b-a and a remains same. So b = 56-42 = 14 & a= 42. 

a = 42, b = 14:

  • Since a>b, we check if a%b=0. Now the answer is yes. 
  • So we print smaller among a and b as H.C.F . i.e. 42 is  3 times of 14.

So HCF is 14. 

C++
#include <iostream> using namespace std;  int gcd(int a, int b) {     // Everything divides 0     if (a == 0)         return b;     if (b == 0)         return a;      // Base case     if (a == b)         return a;      // a is greater     if (a > b) {         if (a % b == 0)             return b;         return gcd(a - b, b);     }      // b is greater     if (b % a == 0)         return a;     return gcd(a, b - a); }  // Driver code int main() {     int a = 20, b = 28;     cout << gcd(a, b);     return 0; } 
Java
class GfG {      static int gcd(int a, int b) {         // Everything divides 0         if (a == 0)             return b;         if (b == 0)             return a;          // Base case         if (a == b)             return a;          // a is greater         if (a > b) {             if (a % b == 0)                 return b;             return gcd(a - b, b);         }          // b is greater         if (b % a == 0)             return a;         return gcd(a, b - a);     }      // Driver code     public static void main(String[] args) {         int a = 20, b = 28;         System.out.println(gcd(a, b));     } } 
Python
def gcd(a, b):     # Everything divides 0     if a == 0:         return b     if b == 0:         return a      # Base case     if a == b:         return a      # a is greater     if a > b:         if a % b == 0:             return b         return gcd(a - b, b)      # b is greater     if b % a == 0:         return a     return gcd(a, b - a)  # Driver code if __name__ == '__main__':     a = 20     b = 28     print(gcd(a, b)) 
C#
using System;  class GfG {     static int gcd(int a, int b) {         // Everything divides 0         if (a == 0)             return b;         if (b == 0)             return a;          // Base case         if (a == b)             return a;          // a is greater         if (a > b)         {             if (a % b == 0)                 return b;             return gcd(a - b, b);         }          // b is greater         if (b % a == 0)             return a;         return gcd(a, b - a);     }      // Driver code     static void Main()     {         int a = 20, b = 28;         Console.WriteLine(gcd(a, b));     } } 
JavaScript
function gcd(a, b) {     // Everything divides 0     if (a === 0)         return b;     if (b === 0)         return a;      // Base case     if (a === b)         return a;      // a is greater     if (a > b) {         if (a % b === 0)             return b;         return gcd(a - b, b);     }      // b is greater     if (b % a === 0)         return a;     return gcd(a, b - a); }  // Driver code let a = 20, b = 28; console.log(gcd(a, b)); 

Output
4

[Approach - 4] Optimized Euclidean Algorithm by Checking Remainder

Instead of the Euclidean algorithm by subtraction, a better approach can be used. We don't perform subtraction here. we continuously divide the bigger number by the smaller number. More can be learned about this efficient solution by using the modulo operator in Euclidean algorithm.

C++
#include <iostream> using namespace std;  // Recursive function to calculate GCD using Euclidean algorithm int gcd(int a, int b) {     return b == 0 ? a : gcd(b, a % b); }  // Driver code int main() {     int a = 20, b = 28;     cout << gcd(a, b);      return 0; } 
Java
class GfG {      // Recursive function to calculate GCD using Euclidean algorithm     static int gcd(int a, int b) {         return (b == 0) ? a : gcd(b, a % b);     }      // Driver code     public static void main(String[] args) {         int a = 20, b = 28;         System.out.println(gcd(a, b));      } } 
Python
# Recursive function to calculate GCD using Euclidean algorithm def gcd(a, b):     return a if b == 0 else gcd(b, a % b)  # Driver code a = 20 b = 28 print(gcd(a, b))  # Output: 4 
C#
using System;  class GfG {     // Recursive function to calculate GCD using Euclidean algorithm     static int gcd(int a, int b) => b == 0 ? a : gcd(b, a % b);      // Driver code     static void Main()     {         int a = 20, b = 28;         Console.WriteLine(gcd(a, b));      } } 
JavaScript
// Recursive function to calculate GCD using Euclidean algorithm function gcd(a, b) {     return b === 0 ? a : gcd(b, a % b); }  // Driver code let a = 20, b = 28; console.log(gcd(a, b)); 

Output
4

Time Complexity: O(log(min(a,b)))

  • Each recursive call reduces the size of the numbers significantly using the modulo operation (a % b), which shrinks the input faster than subtraction.
  • The worst-case scenario for the number of steps occurs when the inputs are consecutive Fibonacci numbers, like (21, 13), which maximizes the number of recursive calls.
  • Since Fibonacci numbers grow exponentially, and the number of steps increases linearly with their position, the time complexity becomes logarithmic in terms of the smaller number — O(log(min(a, b))).

Auxiliary Space: O(log(min(a,b))

  • The maximum number of recursive calls is proportional to the number of steps taken to reduce the input to zero, which is O(log(min(a, b))) in the worst case.

[Approach - 5] Using Built-in Function - O(log(min(a, b))) Time and O(1) Space

Languages like C++ have inbuilt functions to calculate GCD of two numbers.

Below is the implementation using inbuilt functions.

C++
#include <algorithm> #include <iostream> using namespace std;  int gcd(int a, int b) {     return __gcd(a, b); }  // Driver code int main() {     int a = 20, b = 28;     cout << gcd(a, b);     return 0; } 
Java
class GfG {      static int gcd(int a, int b) {         return b == 0 ? a : gcd(b, a % b);     }      // Driver code     public static void main(String[] args) {         int a = 20, b = 28;         System.out.println(gcd(a, b));      } } 
Python
import math  def gcd(a, b):     return math.gcd(a, b)  # Driver code if __name__ == '__main__':     a = 20     b = 28     print(gcd(a, b))   
C#
using System;  class GfG {     static int GCD(int a, int b)     {         return b == 0 ? a : GCD(b, a % b);     }      // Driver code     static void Main()     {         int a = 20, b = 28;         Console.WriteLine(GCD(a, b));      } } 
JavaScript
function gcd(a, b) {     return b === 0 ? a : gcd(b, a % b); }  // Driver code let a = 20, b = 28; console.log(gcd(a, b)); 

Output
4

Please refer GCD of more than two (or array) numbers to find HCF of more than two numbers.


Next Article
Check if two numbers are co-prime or not

K

kartik
Improve
Article Tags :
  • Mathematical
  • DSA
  • Basic Coding Problems
  • SAP Labs
  • GCD-LCM
Practice Tags :
  • SAP Labs
  • Mathematical

Similar Reads

    GCD (Greatest Common Divisor) Practice Problems for Competitive Programming
    GCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two numbers is the largest positive integer that divides both of the numbers.GCD of Two NumbersFastest Way to Compute GCDThe fastest way to find the Greatest Common Divisor (GCD) of two numbers is by using the Euclidean algorithm. The E
    4 min read
    Program to Find GCD or HCF of Two Numbers
    Given two positive integers a and b, the task is to find the GCD of the two numbers.Note: The GCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two numbers is the largest number that divides both of them. Examples:Input: a = 20, b = 28Output: 4Explanation: The factors of 20 are 1, 2, 4
    12 min read
    Check if two numbers are co-prime or not
    Two numbers A and B are said to be Co-Prime or mutually prime if the Greatest Common Divisor of them is 1. You have been given two numbers A and B, find if they are Co-prime or not.Examples : Input : 2 3Output : Co-PrimeInput : 4 8Output : Not Co-PrimeThe idea is simple, we find GCD of two numbers a
    5 min read
    GCD of more than two (or array) numbers
    Given an array arr[] of non-negative numbers, the task is to find GCD of all the array elements. In a previous post we find GCD of two number.Examples:Input: arr[] = [1, 2, 3]Output: 1Input: arr[] = [2, 4, 6, 8]Output: 2Using Recursive GCDThe GCD of three or more numbers equals the product of the pr
    11 min read
    Program to find LCM of two numbers
    Given two positive integers a and b. Find the Least Common Multiple (LCM) of a and b.LCM of two numbers is the smallest number which can be divided by both numbers. Input : a = 10, b = 5Output : 10Explanation : 10 is the smallest number divisible by both 10 and 5Input : a = 5, b = 11Output : 55Expla
    5 min read
    LCM of given array elements
    In this article, we will learn how to find the LCM of given array elements.Given an array of n numbers, find the LCM of it. Example:Input : {1, 2, 8, 3}Output : 24LCM of 1, 2, 8 and 3 is 24Input : {2, 7, 3, 9, 4}Output : 252Table of Content[Naive Approach] Iterative LCM Calculation - O(n * log(min(a
    14 min read
    Find the other number when LCM and HCF given
    Given a number A and L.C.M and H.C.F. The task is to determine the other number B. Examples: Input: A = 10, Lcm = 10, Hcf = 50. Output: B = 50 Input: A = 5, Lcm = 25, Hcf = 4. Output: B = 20 Formula: A * B = LCM * HCF B = (LCM * HCF)/AExample : A = 15, B = 12 HCF = 3, LCM = 60 We can see that 3 * 60
    4 min read
    Minimum insertions to make a Co-prime array
    Given an array of N elements, find the minimum number of insertions to convert the given array into a co-prime array. Print the resultant array also.Co-prime Array : An array in which every pair of adjacent elements are co-primes. i.e, gcd(a, b) = 1 . Examples : Input : A[] = {2, 7, 28}Output : 1Exp
    6 min read
    Find the minimum possible health of the winning player
    Given an array health[] where health[i] is the health of the ith player in a game, any player can attack any other player in the game. The health of the player being attacked will be reduced by the amount of health the attacking player has. The task is to find the minimum possible health of the winn
    4 min read
    Minimum squares to evenly cut a rectangle
    Given a rectangular sheet of length l and width w. we need to divide this sheet into square sheets such that the number of square sheets should be as minimum as possible.Examples: Input :l= 4 w=6 Output :6 We can form squares with side of 1 unit, But the number of squares will be 24, this is not min
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences