gcd of two number in c++ stl
The C++ Standard Library (STL) does not provide a built-in function to calculate the greatest common divisor (gcd) of two numbers. However, you can use the Euclidean algorithm to calculate the gcd. Here is an example of how you can implement it in C++:
#include <iostream>
#include <numeric>
int main() {
int num1 = 12;
int num2 = 18;
int gcd = std::gcd(num1, num2);
std::cout << "GCD of " << num1 << " and " << num2 << " is " << gcd << std::endl;
return 0;
}
In this example, we include the <iostream>
and <numeric>
headers, which are necessary for input and output operations and for using the std::gcd
function, respectively.
We then declare two variables num1
and num2
and initialize them with the numbers for which we want to find the gcd.
Next, we calculate the gcd using the std::gcd
function, which takes two arguments and returns their gcd.
Finally, we use std::cout
to print the result to the console.
When you run this program, it will output:
GCD of 12 and 18 is 6
This means that the gcd of 12 and 18 is 6.
Note that the std::gcd
function was introduced in C++17. If you are using an older version of C++, you can implement the Euclidean algorithm manually.