# Inbuilt function for calculating LCM in C++

In this article, we will talk about the inbuilt functions for calculating LCM in C++ with their syntax and methods.

When programming, we frequently have to determine the Least Common Multiple (LCM) between two numbers. We can just utilize boost::math::lcm(), an intrinsic function of the C++ boost library, rather than creating and utilizing a method to calculate lcm. We must define a header file to use this method.

### Syntax:

It has the following syntax:

Parameters: m, n

Return Value: 0 if either m or n is zero, else lcm of mod(m) and mod(n).

### Program:

Let's take an example to find the lcm using the std::lcm() method in C++.

Output:

```LCM(15, 25) = 75
```

Essential points:

The function takes the modulus of both integers before calculating the LCM; therefore, if either of the numbers is negative, they are first transformed to their modulus before the LCM is computed.

The boost::math::lcm() function will throw an error if any numbers are non-integer data types.

### Program:

Let's take an example to find the lcm using the boost::math::lcm() method in C++.

Since one of the function's arguments is a double type, this code will fail and throw an error.

## Using std::lcm():

A new STL method called std::lcm() has been added to C++17 and can be used with any compiler that supports C++17 features to calculate the LCM of two values.

### Syntax:

It has the following syntax:

Arguments: m, n

Returns: 0 if either of m or n is 0

else, returns lcm of mod(m) and mod(n)

### Program:

Let's take an example to find the lcm using the std::lcm() method in C++.

Output:

```LCM(18, 24) = 72
```

### Key Points:

• This function only accepts positive numbers as inputs; negative inputs are first transformed to their modulus before the LCM is computed.
• Additionally, it can only handle integer data types; an error will be raised if another data type, such as char or double, is supplied as an input.

### There are some common functions for calculating LCM in C++:

Method 1: Finding the GCD and LCM of two numbers with a for-loop

In the example below, the variable I is iterated from 0 to the smaller value using a for loop. The GCD of two integers is eventually obtained if both numbers are divisible by i. Otherwise, the GCD is modified. Next, the LCM of two numbers is computed using the GCD of two numbers.

Program:

Output:

```LCM of 30 and 45 is: 90
```

Method 2: Finding the GCD and LCM of two numbers with a while loop

In the example below, the larger number is substituted with a value obtained by deducting the smaller number from the larger one. The procedure is repeated until the two numbers are equal, at which point the GCD of the two numbers is obtained. Next, the LCM of two numbers is computed using the GCD of two numbers.

Program:

Output:

```LCM of 30 and 45 is: 90
```