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

后端 未结 14 1877

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条回答
  •  Happy的楠姐
    2020-12-07 13:57

    First of all, you have to find the greatest common divisor

    for(int i=1; i<=a && i<=b; i++) {
    
       if (i % a == 0 && i % b == 0)
       {
           gcd = i;
       }
    
    }
    

    After that, using the GCD you can easily find the least common multiple like this

    lcm = a / gcd * b;
    

提交回复
热议问题