std::gcd | C++ inbuilt function for finding GCD
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
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
cout << "gcd(6, 20) = " << __gcd(6, 20) << endl;
}
|
Time Complexity: O(logn)
Auxiliary Space: O(1)
Program to Find the gcd of all numbers in a vector.
C++
#include<bits/stdc++.h>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
vector< int > numbers = { 12, 15, 18, 21, 24 };
int ans =__gcd(numbers[0], numbers[1]);
for ( int i = 2; i < numbers.size(); i++)
{
ans = __gcd(ans, numbers[i]);
}
cout << "The GCD of the numbers in the vector is: " <<ans<<endl;
return 0;
}
|
Output
The GCD of the numbers in the vector is: 3
Time Complexity: O(k*logn)
Auxiliary Space: O(k)
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
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
cout << "gcd(2.0, 8) = " << __gcd(2.0, 8) << endl;
}
|
Output:
Error, As the data type float is not supported by std::gcd.
Last Updated :
31 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...