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

后端 未结 14 1885

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 14:01

    Using Euclidean algorithm to find gcd and then calculating the lcm dividing a by the product of gcd and b worked for me.

    int euclidgcd(int a, int b){
            if(b==0)
            return a;
            int a_rem = a % b;
            return euclidgcd(b, a_rem);
            }
        
    long long lcm(int a, int b) {
            int gcd=euclidgcd(a, b);
            return (a/gcd*b);
            }
    
    int main() {
          int a, b;
          std::cin >> a >> b;
          std::cout << lcm(a, b) << std::endl;
        return 0;           
        }
    
    0 讨论(0)
  • 2020-12-07 14:02

    Product of 2 numbers is equal to LCM * GCD or HCF. So best way to find LCM is to find GCD and divide the product with GCD. That is, LCM(a,b) = (a*b)/GCD(a,b).

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