Skip to content
Related Articles

Related Articles

Improve Article

std::gcd | C++ inbuilt function for finding GCD

  • Difficulty Level : Basic
  • Last Updated : 24 May, 2021

In many competitive programming problems, we need to find greatest common divisor also known as gcd. Euclids algorithm to find gcd has been discussed here.
C++ has the built-in function for calculating GCD. This function is present in header file. 
Syntax for C++14 :

 Library: 'algorithm'
 __gcd(m, n) 
Parameter :  m, n
Return Value :  0 if both m and n are zero, 
else gcd of m and n.

Syntax for C++17 :

Library: 'numeric'
gcd(m, n)
Parameter :  m, n
Return Value :  0 if both m and n are zero,
else gcd of m and n.

CPP




// CPP program to illustrate
// gcd function of C++ STL
#include <iostream>
#include <algorithm>
// #include<numeric> for C++17
 
using namespace std;
 
int main()
{
    cout << "gcd(6, 20) = " << __gcd(6, 20) << endl; // gcd(2.0,8) for C++17
}
Output
gcd(6, 20) = 2

Note: If either M or N is not an integer type, or if either is (possibly cv-qualified) bool, the program is ill-formed. Also, If either |m| or |n| is not representable as a value of type std::common_type_t, the behavior is undefined. 
 

CPP




// CPP program to illustrate
// undefined behavior of
// gcd function of C++ STL
#include <iostream>
#include <algorithm>
// #include<numeric> for C++17
 
using namespace std;
 
int main()
{
    cout << "gcd(6, 20) = " << __gcd(2.0, 8) << endl; // gcd(2.0,8) for C++17
}

Output: 
Error, As the data type float is not supported by std::gcd.
This article is contributed by Pratik Chhajer. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.



My Personal Notes arrow_drop_up
Recommended Articles
Page :