Least Common Multiple of an arbitrary number of positive integers

Join the discussion
Registration is free. Start your own thread to ask a follow-up.
2 replies · 2K views
Jamin2112
Messages
973
Reaction score
12
I need an algorithm for LCM(k1, k2, ..., kn).

Here's what I was thinking:

  • any number ki that divides evenly into another number kj, set ki = 1
  • return k1*k2*...*kn

I'm having trouble implementing it, though.

Code:
int LCM(int* numsPtr, int size) { 
	// assume size > 1 and that array only contains non-negative numbers
	std::vector<int> numsVec(numsPtr, numsPtr + size);
	std::sort(numsVec.begin(), numsVec.begin() + size);
    for (int k = 0; k < size - 1; ++k) { 
		for (int j = k; j < size; ++j) {
			if (numsVec[j] % numsVec[k] == 0) {
				numsVec[k] = 1;
				break;
			}
		}
	}
	int product = 1;
	for (int k = 0; k < size; ++k) 
			product *= numsVec[k];
	return product;
}
 
Last edited:
Physics news on Phys.org
What if you had k1=2*3, k2=2*5, k3=2*7? None evenly divides the other, but the LCM isn't k1*k2*k3, is it?
 
The naive way is to factorize all the numbers.

A less naive way is to find their greatest common divisors. Some guy called Euclid found a neat way to do that.