Oftentimes, we need to find GCD (Greatest Common Divisor) and LCM (Lowest Common Multiple) of two numbers and we tend to implement our own functions in C++ for this purpose.
If you don't know yet, you'll be glad to hear that there are native functions provided by C++ to find GCD and LCM of two integers. It is as simple as that:
int a = 150, b = 225; int gcd_num = gcd(a, b); // returns 75 int lcm_num = lcm(a, b); // returns 450
Let's now move forward and know more about this function.
Include the required header file in order to be able to use the gcd or lcm function. You can either include bits/stdc++.h or include numeric on the top of your .cpp file.
These two functions accept two positive integers as parameters and may throw an error that differs from compiler to compiler or give unexpected results in case unexpected parameters are passed.
- If both numbers are zero, gcd() returns zero.
- If any of the numbers is zero, lcm() returns zero.
There is an interesting relation between the numbers and their respective gcd and lcm. If two numbers are represented as m and n, then
m * n = gcd * lcm
If you already knew this, it is great. If you didn't then now you know. If you know any other interesting things related to it, please write them in the comments.
If you find anything wrong or if you know some more exciting functions or other stuff related to C++, please drop a comment below so we learn together.
My Profile -