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



GCD of Two Numbers in C++

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.

Similar Reads

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....

2. GCD Using Euclidean Algorithm

...

3. GCD Using Inbuilt Function in C++

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....