LCM of Two Numbers in C++
The LCM (Least Common Multiple) of two numbers is the smallest number that is a multiple of both numbers. In C++, we can calculate the LCM of two numbers using different approaches.
Syntax
int lcm(int num1, int num2) {
int lcm = max(num1, num2);
while (true) {
if (lcm % num1 == 0 && lcm % num2 == 0) {
break;
}
lcm++;
}
return lcm;
}
The above code calculates the LCM of two numbers using a brute-force approach. We start by initializing the LCM to the larger of the two numbers and then check if it is a multiple of both numbers. If not, we increment the LCM by 1 and repeat the process until we find the LCM.
Example
#include <iostream>
using namespace std;
int lcm(int num1, int num2) {
int lcm = max(num1, num2);
while (true) {
if (lcm % num1 == 0 && lcm % num2 == 0) {
break;
}
lcm++;
}
return lcm;
}
int main() {
int num1, num2;
cout << "Enter two numbers: ";
cin >> num1 >> num2;
cout << "LCM of " << num1 << " and " << num2 << " is " << lcm(num1, num2) << endl;
return 0;
}
Output
Enter two numbers: 4 6
LCM of 4 and 6 is 12
Explanation
In the above example, we have defined a function called "lcm" that takes two integers as arguments and returns their LCM. We then use this function to calculate the LCM of two numbers input by the user.
Use
The LCM of two numbers is a commonly used mathematical concept in computer science algorithms and programming. It can be used in various applications like calculating the period of a repeating decimal, finding the least common denominator in fraction addition, and more.
Important Points
- The LCM of two numbers is the smallest number that is a multiple of both numbers.
- We can use a brute-force approach to calculate the LCM of two numbers.
- The std::lcm() function can be used in C++17 and above.
Summary
In summary, the LCM of two numbers is an important mathematical concept that can be calculated in C++ using different approaches. The std::lcm() function is available in C++17 and above for an efficient and reliable approach.