Open In App

lcm() in C++ 17

Last Updated : 27 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The lcm() is a built-in function introduced in C++17. It is used to calculate the least common multiple (LCM) of two integers. The LCM of two integers is the smallest positive integer that is divisible by both numbers.

Let’s take a look at an example that illustrates the lcm() function:

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    int a = 12, b = 18;

    // Compute LCM of 12 and 18
    cout << lcm(a, b);

    return 0;
}


Output

36

This article covers the syntax, usage, and common examples of the lcm() function in C++:

Syntax of lcm()

The lcm() function is defined in the <numeric> header.

lcm(a, b);

Parameters:

  • a: The first integer.
  • b: The second integer.

Return Value:

  • Returns the least common multiple of the two integers.
  • If either a or b is zero, the LCM is defined as 0.

Time Complexity: O(log(min(a,b)))

Auxiliary Space: O(1)

Note: The lcm() function works only on integer data type, and if any other data type like char, double, is provided in its argument, then it will throw an error.

Examples of lcm()

The following code examples demonstrates how we can use the lcm() function in different scenarios:

LCM of Negative Numbers

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    int a = -15, b = -20;

    // Compute LCM of -15 and -20
    cout << lcm(a, b);

    return 0;
}


Output

60

Find the LCM of Numbers in a Vector

We can use the accumulate() function along with lcm() function from <numeric> to compute the LCM of multiple numbers in a vector.

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {4, 6, 8, 12};

    // Compute LCM of all numbers
    int res = accumulate(v.begin(), v.end(), 1, lcm<int, int>);

    cout << res;
    return 0;
}


Output

24

Next Article
Article Tags :
Practice Tags :

Similar Reads