What is the most efficient way to calculate the least common multiple of two integers?

What is the most efficient way to calculate the least common multiple of two integers?

I just came up with this, but it definitely leaves something to be desired.

int n=7, m=4, n1=n, m1=m;


while( m1 != n1 ){
if( m1 > n1 )
n1 += n;
else
m1 += m;
}


System.out.println( "lcm is " + m1 );
95847 次浏览

Take successive multiples of the larger of the two numbers until the result is a multiple of the smaller.

this might work..

   public int LCM(int x, int y)
{
int larger  = x>y? x: y,
smaller = x>y? y: x,
candidate = larger ;
while (candidate % smaller  != 0) candidate += larger ;
return candidate;
}

The least common multiple (lcm) of a and b is their product divided by their greatest common divisor (gcd) ( i.e. lcm(a, b) = ab/gcd(a,b)).

So, the question becomes, how to find the gcd? The Euclidean algorithm is generally how the gcd is computed. The direct implementation of the classic algorithm is efficient, but there are variations that take advantage of binary arithmetic to do a little better. See Knuth's "The Art of Computer Programming" Volume 2, "Seminumerical Algorithms" § 4.5.2.

I think that the approach of "reduction by the greatest common divider" should be faster. Start by calculating the GCD (e.g. using Euclid's algorithm), then divide the product of the two numbers by the GCD.

Remember The least common multiple is the least whole number that is a multiple of each of two or more numbers.

If you are trying to figure out the LCM of three integers, follow these steps:

  **Find the LCM of 19, 21, and 42.**

Write the prime factorization for each number. 19 is a prime number. You do not need to factor 19.

21 = 3 × 7
42 = 2 × 3 × 7
19

Repeat each prime factor the greatest number of times it appears in any of the prime factorizations above.

2 × 3 × 7 × 19 = 798

The least common multiple of 21, 42, and 19 is 798.

First of all, you have to find the greatest common divisor

for(int i=1; i<=a && i<=b; i++) {


if (i % a == 0 && i % b == 0)
{
gcd = i;
}


}

After that, using the GCD you can easily find the least common multiple like this

lcm = a / gcd * b;

I don't know whether it is optimized or not, but probably the easiest one:

public void lcm(int a, int b)
{
if (a > b)
{
min = b;
max = a;
}
else
{
min = a;
max = b;
}
for (i = 1; i < max; i++)
{
if ((min*i)%max == 0)
{
res = min*i;
break;
}
}
Console.Write("{0}", res);
}

Best solution in C++ below without overflowing

#include <iostream>
using namespace std;
long long gcd(long long int a, long long int b){
if(b==0)
return a;
return gcd(b,a%b);
}


long long lcm(long long a,long long b){
if(a>b)
return (a/gcd(a,b))*b;
else
return (b/gcd(a,b))*a;
}


int main()
{
long long int a ,b ;
cin>>a>>b;
cout<<lcm(a,b)<<endl;
return 0;
}

C++ template. Compile time

#include <iostream>


const int lhs = 8, rhs = 12;


template<int n, int mod_lhs=n % lhs, int mod_rhs=n % rhs> struct calc {
calc() { }
};


template<int n> struct calc<n, 0, 0> {
calc() { std::cout << n << std::endl; }
};


template<int n, int mod_rhs> struct calc<n, 0, mod_rhs> {
calc() { }
};


template<int n, int mod_lhs> struct calc <n, mod_lhs, 0> {
calc() { }
};


template<int n> struct lcm {
lcm() {
lcm<n-1>();
calc<n>();
}
};


template<> struct lcm<0> {
lcm() {}
};


int main() {
lcm<lhs * rhs>();
}

Product of 2 numbers is equal to LCM * GCD or HCF. So best way to find LCM is to find GCD and divide the product with GCD. That is, LCM(a,b) = (a*b)/GCD(a,b).

Euclidean GCD code snippet

int findGCD(int a, int b) {
if(a < 0 || b < 0)
return -1;


if (a == 0)
return b;
else if (b == 0)
return a;
else
return findGCD(b, a % b);
}

Here is a highly efficient approach to find the LCM of two numbers in python.

def gcd(a, b):
if min(a, b) == 0:
return max(a, b)
a_1 = max(a, b) % min(a, b)
return gcd(a_1, min(a, b))


def lcm(a, b):
return (a * b) // gcd(a, b)

There is no way more efficient than using a built-in function!

As of Python 3.8 lcm() function has been added in math library. And can be called with folowing signature:

math.lcm(*integers)

Returns the least common multiple of the specified integer arguments. If all arguments are nonzero, then the returned value is the smallest positive integer that is a multiple of all arguments. If any of the arguments is zero, then the returned value is 0. lcm() without arguments returns 1.

Using Euclidean algorithm to find gcd and then calculating the lcm dividing a by the product of gcd and b worked for me.

int euclidgcd(int a, int b){
if(b==0)
return a;
int a_rem = a % b;
return euclidgcd(b, a_rem);
}
    

long long lcm(int a, int b) {
int gcd=euclidgcd(a, b);
return (a/gcd*b);
}


int main() {
int a, b;
std::cin >> a >> b;
std::cout << lcm(a, b) << std::endl;
return 0;
}

Extending @John D. Cook answer that is also marked answer for this question. ( https://stackoverflow.com/a/3154503/13272795), I am sharing algorithm to find LCM of n numbers, it maybe LCM of 2 numbers or any numbers. Source for this code is this

 int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}


// Returns LCM of array elements
ll findlcm(int arr[], int n)
{
// Initialize result
ll ans = arr[0];


// ans contains LCM of arr[0], ..arr[i]
// after i'th iteration,
for (int i = 1; i < n; i++)
ans = arr[i] * ans/gcd(arr[i], ans);
return ans;
}

Since we know the mathematic property which states that "product of LCM and HCF of any two numbers is equal to the product of the two numbers".

lets say X and Y are two integers, then X * Y = HCF(X, Y) * LCM(X, Y)

Now we can find LCM by knowing the HCF, which we can find through Euclidean Algorithm.

  LCM(X, Y) = (X * Y) / HCF(X, Y)

Hope this will be efficient.

import java.util.*;
public class Hello {
public static int HCF(int X, int Y){
if(X == 0)return Y;
return HCF(Y%X, X);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int X = scanner.nextInt(), Y = scanner.nextInt();
System.out.print((X * Y) / HCF(X, Y));
}
}

Yes, there are numerous way to calculate LCM such as using GCD (HCF). You can apply prime decomposition such as (optimized/naive) Sieve Eratosthenes or find factor of prime number to compute GCD, which is way more faster than calculate LCM directly. Then as all said above, LCM(X, Y) = (X * Y) / GCD(X, Y)

I googled the same question, and found this Stackoverflow page, however I come up with another simple solution using python

def find_lcm(numbers):
h = max(numbers)


lcm = h


def check(l, numbers):
remainders = [ l%n==0 for n in numbers]
return all(remainders)


while (check(lcm, numbers) == False):
lcm = lcm + h
    

return lcm




numbers = [120,150,135,225] it will return 5400

numbers = [120,150,135,225]


print(find_lcm(numbers)) # will print 5400