What is the most efficient way to calculate the least common multiple of two integers?

后端 未结 14 1888

What is the most efficient way to calculate the least common multiple of two integers?

I just came up with this, but it definitely leaves something to be desired.

14条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-07 13:47

    I don't know whether it is optimized or not, but probably the easiest one:

    public void lcm(int a, int b)
    {
        if (a > b)
        {
            min = b;
            max = a;
        }
        else
        {
            min = a;
            max = b;
        }
        for (i = 1; i < max; i++)
        {
            if ((min*i)%max == 0)
            {
                res = min*i;
                break;
            }
        }
        Console.Write("{0}", res);
    }
    

提交回复
热议问题