Search code examples
javac++mathlcm

How to find Least Common Multiple (LCM) for two numbers


I have used Euclid's method to find the L.C.M for two numbers.

l.c.m=a*b/(gcd(a,b))

How can I do this without using this algorithm? I have an idea of first getting all factors of these two numbers and storing them in array. Then take 1 element from array 1 and search for it in array2, if it present there then remove it from there and make the result multiply by that num.

Is this OK?


Solution

  • Almost. What's the LCM of 4 and 8? Obviously 8 (23), but in your method you'd find 2. You need to keep track not just of all factors, but also how often they appear.