Program to Find GCD or HCF of Two Numbers
Last Updated :
29 Jul, 2025
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 = 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.
[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));
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));
[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));
[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));
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
import java.math.BigInteger;
class GfG {
public static void main(String[] args) {
int a = 20, b = 28;
// Convert to BigInteger and compute GCD
int gcd = BigInteger.valueOf(a).gcd(BigInteger.valueOf(b)).intValue();
System.out.println(gcd);
}
}
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));
Please refer GCD of more than two (or array) numbers to find HCF of more than two numbers.
Program to find GCD or HCF of two numbers
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem