C++ algorithm to calculate least common multiple for multiple numbers

后端 未结 15 1939
太阳男子
太阳男子 2020-12-14 16:29

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)?

15条回答
  •  旧时难觅i
    2020-12-14 17:01

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

    GCD (a, b, c) = GCD (a, GCD (b, c))
                  = GCD (b, GCD (a, c))
                  = GCD (c, GCD (a, b))
                  = ...
    

    To calculate the LCM, use...

                    a * b
    LCM (a, b) = ----------
                 GCD (a, b)
    

    The logic for that is based on prime factorization. The more general form (more than two variables) is...

                                              a                 b        
    LCM (a, b, ...) = GCD (a, b, ...) * --------------- * --------------- * ...
                                        GCD (a, b, ...)   GCD (a, b, ...)
    

    EDIT - actually, I think that last bit may be wrong. The first LCM (for two parameters) is right, though.

提交回复
热议问题