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

后端 未结 15 1755
太阳男子
太阳男子 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条回答
  • 2020-12-14 17:17

    Using the fact that lcm should be divisible by all the numbers in list. Here the list is a vector containing numbers

            int lcm=*(len.begin());
        int ini=lcm;
        int val;
        int i=1;
        for(it=len.begin()+1;it!=len.end();it++)
        {
            val=*it;
            while(lcm%(val)!=0)
            {
                lcm+=ini;
            }
            ini=lcm;
        }
        printf("%llu\n",lcm);
        len.clear();
    
    0 讨论(0)
  • 2020-12-14 17:18

    I found this while searching a similar problem and wanted to contribute what I came up with for two numbers.

    #include <iostream>
    #include <algorithm>
    using namespace std;
    
    int main()
    {
        cin >> x >> y;
    
        // zero is not a common multiple so error out
        if (x * y == 0)
            return -1;
    
        int n = min(x, y);
        while (max(x, y) % n)
            n--;
    
        cout << n << endl;
    }
    
    0 讨论(0)
  • 2020-12-14 17:19
    #include
    #include
    
    void main()
    {
        clrscr();
    
        int x,y,gcd=1;
    
        cout<>x;
    
        cout<>y;
    
        for(int i=1;i<1000;++i)
        {
            if((x%i==0)&&(y%i==0))
            gcd=i;
        }
    
        cout<<"\n\n\nGCD :"<
        cout<<"\n\n\nLCM :"<<(x*y)/gcd;
    
        getch();
    }
    
    0 讨论(0)
  • 2020-12-14 17:20

    As of C++17, you can use std::lcm.

    And here is a little program that shows how to specialize it for multiple parameters

    #include <numeric>
    #include <iostream>
    
    namespace math {
    
        template <typename M, typename N>
        constexpr auto lcm(const M& m, const N& n) {
            return std::lcm(m, n);
        }
    
        template <typename M, typename ...Rest>
        constexpr auto lcm(const M& first, const Rest&... rest) {
            return std::lcm(first, lcm(rest...));
        }
    }
    
    auto main() -> int {
        std::cout << math::lcm(3, 6, 12, 36) << std::endl;
        return 0;
    }
    

    See it in action here: https://wandbox.org/permlink/25jVinGytpvPaS4v

    0 讨论(0)
  • 2020-12-14 17:22

    boost provides functions for calculation lcm of 2 numbers (see here)

    Then using the fact that

    lcm(a,b,c) = lcm(lcm(a,b),c)
    

    You can easily calculate lcm for multiple numbers as well

    0 讨论(0)
  • 2020-12-14 17:22

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

    0 讨论(0)
提交回复
热议问题