Least Common Multiple of an arbitrary number of positive integers

Click For Summary
SUMMARY

The discussion focuses on developing an algorithm to compute the Least Common Multiple (LCM) of an arbitrary number of positive integers using C++. The proposed implementation utilizes a sorting mechanism and checks for divisibility to simplify the input numbers. However, it highlights a flaw in the naive approach of multiplying the numbers directly, especially when they do not evenly divide each other. The conversation suggests leveraging the Euclidean algorithm to find the greatest common divisor (GCD) as a more efficient method for calculating the LCM.

PREREQUISITES
  • C++ programming language proficiency
  • Understanding of algorithms and their complexities
  • Knowledge of the Euclidean algorithm for GCD calculation
  • Familiarity with vector operations in C++
NEXT STEPS
  • Implement the Euclidean algorithm for GCD in C++
  • Research efficient LCM calculation methods using GCD
  • Explore C++ STL functions for optimizing vector operations
  • Study algorithm complexity analysis for LCM algorithms
USEFUL FOR

Software developers, algorithm enthusiasts, and students studying number theory or C++ programming who are interested in optimizing mathematical computations.

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:
Technology 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.
 

Similar threads

  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 15 ·
Replies
15
Views
3K
  • · Replies 75 ·
3
Replies
75
Views
7K
  • · Replies 25 ·
Replies
25
Views
3K
Replies
47
Views
5K
  • · Replies 6 ·
Replies
6
Views
12K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 36 ·
2
Replies
36
Views
5K
  • · Replies 17 ·
Replies
17
Views
3K