Is there a C++ algorithm to calculate the least common multiple for multiple numbers, like lcm(3,6,12)
or lcm(5,7,9,12)
?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- What are the problems associated to Best First Sea
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
The algorithm isn't specific to C++. AFAIK, there's no standard library function.
To calculate the LCM, you first calculate the GCD (Greatest Common Divisor) using Euclids algorithm.
http://en.wikipedia.org/wiki/Greatest_common_divisor
The GCD algorithm is normally given for two parameters, but...
To calculate the LCM, use...
The logic for that is based on prime factorization. The more general form (more than two variables) is...
EDIT - actually, I think that last bit may be wrong. The first LCM (for two parameters) is right, though.
I just created gcd for multiple numbers:
dbd - gcd.
n - number of numbers.
The Codes given above only discusses about evaluating LCM for multiple numbers however it is very likely to happen that while performing multiplications we may overflow integer limit for data type storage
*A Corner Case :- *
e.g. if while evaluating you reach situation such that if LCM_till_now=1000000000000000 next_number_in_list=99999999999999 and Hence GCD=1 (as both of them are relatively co-prime to each other)
So if u perform operation (LCM_till_now*next_number_in_list) will not even fit in "unsigned long long int"
Remedy :- 1.Use Big Integer Class 2.Or if the problem is asking for LCM%MOD----------->then apply properties of modular arithmetic.
If you look at this page, you can see a fairly simple algorithm you could use. :-)
I'm not saying it's efficient or anything, mind, but it does conceptually scale to multiple numbers. You only need space for keeping track of your original numbers and a cloned set that you manipulate until you find the LCM.
Not built in to the standard library. You need to either build it yourself or get a library that did it. I bet Boost has one...
I found this while searching a similar problem and wanted to contribute what I came up with for two numbers.