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

后端 未结 15 1937
太阳男子
太阳男子 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();
    

提交回复
热议问题