The Wayback Machine - https://web.archive.org/web/20240912102756/https://www.geeksforgeeks.org/gcd-in-cpp/
Open In App

GCD of Two Numbers in C++

Last Updated : 01 Aug, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

GCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two numbers is the largest number that exactly divides both numbers. In this article, we will learn to write a C++ program to find the GCD of two numbers.

GCD or HCF of Two Numbers

1. GCD Using Simple Method

The idea is to find the minimum of the two numbers and then find the common divisor starting from the minimum number and decrementing it by 1 until a common divisor is found.

Algorithm

  • Initialize a variable result with the minimum of a and b.
  • Run a loop till the result > 0.
  • If both numbers are divisible by the variable result, break the loop.
  • Else, decrement the result variable by 1.
  • After the loop, the result variable holds the GCD of the two numbers.
  • Return the result variable.

C++ Program To Find GCD of Two Numbers Using Simple Method

C++




// C++ program to find GCD of two numbers
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to return gcd of a and b
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;
}
  
// Driver code
int main()
{
    int a = 98, b = 56;
    cout << "GCD of " << a << " and " << b << " is "
         << gcd(a, b);
    return 0;
}
// This code is contributed by Suruchi Kumari


Output

GCD of 98 and 56 is 14

2. GCD Using Euclidean Algorithm

The Euclidean algorithm is an efficient method to find the GCD of two numbers. It works on the principle that the GCD of two numbers remains the same if the greater number is replaced by the difference between the two numbers.

Algorithm

  • Define a function that takes two integers to find their GCD.
  • If a is equal to 0, then the GCD of a and b is b.
  • If b is equal to 0, then the GCD of a and b is a.
  • If a and b are equal, the GCD is a or b.
  • If a > b, call the gcd function recursively with parameters (a – b, b).
  • Else, call the gcd function recursively with parameters (a, b-a).

C++ Program to Find GCD of Two Numbers Using Euclidean Algorithm

C++




// C++ program to find GCD
// of two numbers
#include <iostream>
using namespace std;
  
// Recursive function to return
// gcd of a and b
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);
}
  
// Driver code
int main()
{
    int a = 98, b = 56;
    cout << "GCD of " << a << " and " << b << " is "
         << gcd(a, b);
    return 0;
}


Output

GCD of 98 and 56 is 14

Explanation

a = 98 and b = 56
a > b so put a = a - b and b remains the same.
So a = 98 - 56 = 42 and b = 56. 
Now b > a so b = b - a and a is same b= 56-42 = 14 & a= 42. 
42 is 3 times 14
HCF is 14.

Complexity Analysis

  • Time Complexity: O(min(a,b))
  • Auxiliary Space: O(min(a,b))

3. GCD Using Inbuilt Function in C++

In C++ Standard Library, there is an inbuilt function __gcd() in <algorithm> header file to find the gcd of two numbers.

Syntax

 __gcd(num1, num2)

where num1 and num2 are the two numbers.

C++ Program to Find the GCD of Two Numbers Using Inbuilt Functions

C++




// CPP program to find gcd of two numbers using inbuilt
// __gcd() function
  
// #include<numeric> for C++17
#include <algorithm>
#include <iostream>
  
using namespace std;
  
int main()
{
    cout << "gcd(10, 20) = " << __gcd(10, 20) << endl;
}


Output

gcd(10, 20) = 10

Complexity Analysis

  • Time Complexity: O(log n)
  • Auxiliary Space: O(1)

Please refer to the complete article Program to Find GCD or HCF of Two Numbers for more methods to find the GCD of two numbers.

Related Articles



Similar Reads

C++ Program for GCD of more than two (or array) numbers
The GCD of three or more numbers equals the product of the prime factors common to all the numbers, but it can also be calculated by repeatedly taking the GCDs of pairs of numbers. gcd(a, b, c) = gcd(a, gcd(b, c)) = gcd(gcd(a, b), c) = gcd(gcd(a, c), b) C/C++ Code // C++ program to find GCD of two or // more numbers #include &lt;bits/stdc++.h&gt; u
3 min read
Number of ways to obtain each numbers in range [1, b+c] by adding any two numbers in range [a, b] and [b, c]
Given three integers a, b and c. You need to select one integer from the range [a, b] and one integer from the range [b, c] and add them. The task to calculate the number of ways to obtain the sum for all the numbers in the range [1, b+c]. Examples: Input: a = 1, b = 2, c = 2 Output: 0, 0, 1, 1 Explanation: The numbers to be obtained are [1, b+c] =
10 min read
Find the ratio of LCM to GCD of a given Array
Given an array arr[] of positive integers, the task is to find the ratio of LCM and GCD of the given array.Examples: Input: arr[] = {2, 3, 5, 9} Output: 90:1 Explanation: The GCD of the given array is 1 and the LCM is 90. Therefore, the ratio is evaluated as 90:1.Input: arr[] = {6, 12, 36} Output: 6:1 Explanation: The GCD of the given array is 6 an
7 min read
Find unique lexicographically increasing quadruplets with sum as B and GCD of absolute values of all elements is 1
Given an array A of size N and an integer B, the task is to find all unique quadruplets arranged in the lexicographically increasing order such that the sum of the elements of each quadrupled is B and the gcd of the absolute values of all elements of a quadrupled is 1. Example: Input: A = {1, 0, -1, 0, -2, 2 }, B = 0Output:-2 -1 1 2-1 0 0 1Explanat
11 min read
Check if a given pair of Numbers are Betrothed numbers or not
Given two positive numbers N and M, the task is to check whether the given pairs of numbers (N, M) form a Betrothed Numbers or not. Examples: Input: N = 48, M = 75 Output: Yes Explanation: The proper divisors of 48 are 1, 2, 3, 4, 6, 8, 12, 16, 24 Sum of proper divisors of 48 is 75(sum1) The proper divisors of 75 are 1, 3, 5, 15, 25 Sum of proper d
7 min read
C++ Program to Rotate all odd numbers right and all even numbers left in an Array of 1 to N
Given a permutation arrays A[] consisting of N numbers in range [1, N], the task is to left rotate all the even numbers and right rotate all the odd numbers of the permutation and print the updated permutation. Note: N is always even.Examples:  Input: A = {1, 2, 3, 4, 5, 6, 7, 8} Output: {7, 4, 1, 6, 3, 8, 5, 2} Explanation: Even element = {2, 4, 6
2 min read
Find numbers starting from 1 with sum at-most K excluding given numbers
Given an array arr[] and an integer K, the task is to find the numbers starting from 1 with sum at-most K excluding elements of the given arrayExamples: Input: arr[] = {4, 6, 8, 12}, K = 14Output: {1, 2, 3, 5}Explanation: Maximum possible sum is 11, with elements as 1, 2, 3 and 5 Input: arr[] = {1, 3, 4}, K = 7Output: {2, 5}Explanation: Maximum pos
5 min read
Divide the two given numbers by their common divisors
Given two numbers A and B, the task is to Divide the two numbers A and B by their common divisors. The numbers A and B is less than 10^8.Examples: Input: A = 10, B = 15 Output: A = 2, B = 3 The common factors are 1, 5 Input: A = 100, B = 150 Output: A = 2, B = 3 Naive Approach: Iterate from i = 1 to minimum of A and B and check whether i is a facto
10 min read
C++ Program for Common Divisors of Two Numbers
Given two integer numbers, the task is to find the count of all common divisors of given numbers. Input : a = 12, b = 24 Output: 6 // all common divisors are 1, 2, 3, // 4, 6 and 12 Input : a = 3, b = 17 Output: 1 // all common divisors are 1 Input : a = 20, b = 36 Output: 3 // all common divisors are 1, 2, 4 // C++ implementation of program #inclu
2 min read
Subtraction of two numbers using 2's Complement
Given two numbers a and b. The task is to subtract b from a by using 2's Complement method.Note: Negative numbers represented as 2's Complement of Positive Numbers.For example, -5 can be represented in binary form as 2's Complement of 5. Look at the image below: Examples: Input : a = 2, b = 3 Output : -1 Input : a = 9, b = 7 Output : 2 To subtract
12 min read
Count the number of carry operations required to add two numbers
Given two numbers, the task is to find the number of carry operations required when two numbers are added as below. 1234 + 5678 -------- 6912 -------- Examples: Input: n = 1234, k = 5678 Output: 2 4+8 = 2 and carry 1 carry+3+7 = carry 1 carry+2+6 = 9, carry 0 carry+1+5 = 6 Input: n = 555, k = 555 Output: 3 Approach: Store the values of n and k in s
8 min read
Reach the numbers by making jumps of two given lengths
Given integers k, d1, d2 and an integer array arr[]. Starting from number k you are allowed to make jumps of size d1 and d2 i.e. all the possible moves from k are: k + d1 and k - d1k + d2 and k - d2 The task is to find which of the numbers from the array are reachable from k making any number of jumps and any given jump is either of size d1 or d2.
8 min read
Count common prime factors of two numbers
Given two integer [Tex]A [/Tex]and [Tex]B [/Tex], the task is to find the count of common factors of two numbers where factors are prime.Examples: Input: A = 6, B = 12 Output: 2 2 and 3 are the only common prime divisors of 6 and 12Input: A = 4, B = 8 Output: 1 Naive Approach: Iterate from 1 to min(A, B) and check whether i is prime and a factor of
10 min read
Program to find LCM of two Fibonacci Numbers
Given here are two positive numbers a and b. The task is to print the least common multiple of a'th and b'th Fibonacci Numbers.The first few Fibonacci Numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ......Note that 0 is considered as 0’th Fibonacci Number.Examples: Input : a = 3, b = 12 Output : 144 Input : a = 8, b = 37 Output : 50731415
8 min read
Find two Composite Numbers such that there difference is N
Given a number N, the task is to find two composite numbers X and Y, such that difference between them is equal to N. Note that there can be multiple answers for this task. Print any one of them.Examples: Input: N = 4 Output: X = 36, Y = 32 Input: N = 1 Output: X = 9, Y = 8 Approach: We have to find X - Y = N. We know, minimum value of N can be 0 o
3 min read
Find two numbers with the given LCM and minimum possible difference
Given an integer X, the task is to find two integers A and B such that LCM(A, B) = X and the difference between the A and B is minimum possible.Examples: Input: X = 6 Output: 2 3 LCM(2, 3) = 6 and (3 - 2) = 1 which is the minimum possible.Input X = 7 Output: 1 7 Approach: An approach to solve this problem is to find all the factors of the given num
5 min read
Subtraction of two large numbers using 9's complement
Given two strings str1 and str2 of given lengths N and M respectively, each representing a large number, the task is to subtract one from the other using 9's complement.Examples: Input: N = 17, str1 = "12345678987654321", M = 11, str2 = "22324324343" Output: 12345656663329978Input: N = 20, Str1 = "12345334233242431433", M = 20, Str2 = "123453342332
12 min read
Subtraction of two large numbers using 10's complement
Given two strings str1 and str2 of given lengths N and M respectively, each representing a large number, the task is to subtract one from the other using 10's complement. Example: Input: N = 10, str1 = “3434243434”, M = 14, str2 = “22324365765767” Output: 22320931522333 Input: N = 20, str1 = “12345334233242431433”, M = 20, str2 = “12345334233242431
13 min read
Split squares of first N natural numbers into two sets with minimum absolute difference of their sums
Given an integer N, the task is to partition the squares of first N( always a multiple of 8 ) natural numbers into two sets such that the difference of their subset sums is minimized. Print both the subsets as the required answer. Examples: Input: N = 8Output:01 16 36 494 9 25 64Explanation: Squares of first N natural numbers are {1, 4, 9, 16, 25,
9 min read
C++ Program to Check if two numbers are bit rotations of each other or not
Given two positive integers x and y, check if one integer is obtained by rotating bits of other. Input constraint: 0 &lt; x, y &lt; 2^32 Bit Rotation: A rotation (or circular shift) is an operation similar to shift except that the bits that fall off at one end are put back to the other end.More information on bit rotation can be found hereExample 1
3 min read
Swapping two numbers using template function in C++
A significant benefit of object-oriented programming is the reusability of code which eliminates redundant coding. An important feature of C++ is called templates. Templates support generic programming, which allows to development of reusable software components such as functions, classes, etc., supporting different data types in a single framework
2 min read
C++ Program To Add Two Complex Numbers
Given two complex numbers of the form and the task is to add these two complex numbers. a1 + ib1 and a2 + ib2 Here the values of real and imaginary numbers are passed while calling the parameterized constructor and, with the help of a default(empty) constructor, the function addComp is called to get the addition of complex numbers. Examples: Input:
3 min read
C++ Program To Find Armstrong Numbers Between Two Integers
A positive integer with digits a, b, c, d... is called an Armstrong number of order n if following condition is satisfied.  abcd... = an + bn + cn + dn +... 153 = 1*1*1 + 5*5*5 + 3*3*3 = 1 + 125 + 27 = 153 Therefore, 153 is an Armstrong number. Examples: Input: 100 400 Output: 153 370 371 Explanation: 100 and 400 are given two integers.(interval) 1
2 min read
C++ Program To Check If a Prime Number Can Be Expressed as Sum of Two Prime Numbers
Given a prime number [Tex]N  [/Tex]. The task is to check if it is possible to express [Tex]N  [/Tex]as sum of two separate prime numbers.Note: The range of N is less than 108. Examples:  Input: N = 13 Output: Yes Explanation: The number 13 can be written as 11 + 2, here 11 and 2 are both prime. Input: N = 11 Output: No Simple Solution: A simple so
2 min read
C++ Program To Multiply Two Floating-Point Numbers
Here, we will see how to multiply two floating-point numbers using the C++ program. Floating point numbers are numbers that include both integer part and fractional parts represented in the form of decimal and exponential values. float data type is used to store floating point values. For example Input : A =1.2, B = 3.0 Output : 3.6 We can multiply
2 min read
C++ Program To Find LCM of Two Numbers
LCM (Least Common Multiple) of two numbers is the smallest number that is divisible by both numbers. For example, the LCM of 15 and 20 is 60, and the LCM of 15 and 25 is 75. In this article, we will learn to write a C++ program to find the LCM of two numbers. We can find the LCM of two numbers in C++ using two methods: 1. LCM of Two Numbers Using S
4 min read
C++ Program To Add Two Numbers Represented By Linked Lists- Set 1
Given two numbers represented by two lists, write a function that returns the sum list. The sum list is a list representation of the addition of two input numbers. Example: Input: List1: 5-&gt;6-&gt;3 // represents number 563 List2: 8-&gt;4-&gt;2 // represents number 842 Output: Resultant list: 1-&gt;4-&gt;0-&gt;5 // represents number 1405 Explanat
12 min read
C++ Program For Adding Two Numbers Represented By Linked Lists- Set 2
Given two numbers represented by two linked lists, write a function that returns the sum list. The sum list is linked list representation of the addition of two input numbers. It is not allowed to modify the lists. Also, not allowed to use explicit extra space (Hint: Use Recursion). Example : Input: First List: 5-&gt;6-&gt;3 Second List: 8-&gt;4-
8 min read
C++ Program To Multiply Two Numbers Represented By Linked Lists
Given two numbers represented by linked lists, write a function that returns the multiplication of these two linked lists. Examples: Input: 9-&gt;4-&gt;6 8-&gt;4 Output: 79464 Input: 3-&gt;2-&gt;1 1-&gt;2 Output: 3852Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Solution: Traverse both lists and generate the re
3 min read
C++ Program To Subtract Two Numbers Represented As Linked Lists
Given two linked lists that represent two large positive numbers. Subtract the smaller number from the larger one and return the difference as a linked list. Note that the input lists may be in any order, but we always need to subtract smaller from the larger ones.It may be assumed that there are no extra leading zeros in input lists.Examples: Inpu
5 min read
Practice Tags :