DEV Community

loading...
Cover image for Factor Operations: gcd and lcm functions in C++

Factor Operations: gcd and lcm functions in C++

satyam1203 profile image Satyam Lachhwani ・2 min read

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
Enter fullscreen mode Exit fullscreen mode

Let's now move forward and know more about this function.

Use

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.

Accepted function parameters

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.

Things to keep in mind

  • 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
Enter fullscreen mode Exit fullscreen mode

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.

For full reference, visit gcd and lcm

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 -

Github
LinkedIn

Discussion (1)

pic
Editor guide
Collapse
pgradot profile image
Pierre Gradot

Once I discover new functions in the standard library XD

Don't use bits/stdc++.h in real life code: geeksforgeeks.org/bitsstdc-h-c/