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

后端 未结 14 1886

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:50

    Here is a highly efficient approach to find the LCM of two numbers in python.

    def gcd(a, b):
        if min(a, b) == 0:
            return max(a, b)
        a_1 = max(a, b) % min(a, b)
        return gcd(a_1, min(a, b))
    
    def lcm(a, b):
        return (a * b) // gcd(a, b)
    
    0 讨论(0)
  • 2020-12-07 13:51

    Remember The least common multiple is the least whole number that is a multiple of each of two or more numbers.

    If you are trying to figure out the LCM of three integers, follow these steps:

      **Find the LCM of 19, 21, and 42.**
    

    Write the prime factorization for each number. 19 is a prime number. You do not need to factor 19.

    21 = 3 × 7
    42 = 2 × 3 × 7
    19
    

    Repeat each prime factor the greatest number of times it appears in any of the prime factorizations above.

    2 × 3 × 7 × 19 = 798

    The least common multiple of 21, 42, and 19 is 798.

    0 讨论(0)
  • 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;
    
    0 讨论(0)
  • 2020-12-07 13:59

    I think that the approach of "reduction by the greatest common divider" should be faster. Start by calculating the GCD (e.g. using Euclid's algorithm), then divide the product of the two numbers by the GCD.

    0 讨论(0)
  • 2020-12-07 13:59

    There is no way more efficient than using a built-in function!

    As of Python 3.8 lcm() function has been added in math library. And can be called with folowing signature:

    math.lcm(*integers)
    

    Returns the least common multiple of the specified integer arguments. If all arguments are nonzero, then the returned value is the smallest positive integer that is a multiple of all arguments. If any of the arguments is zero, then the returned value is 0. lcm() without arguments returns 1.

    0 讨论(0)
  • 2020-12-07 14:01

    Best solution in C++ below without overflowing

    #include <iostream>
    using namespace std; 
    long long gcd(long long int a, long long int b){        
        if(b==0)
            return a;
        return gcd(b,a%b);
    }
    
    long long lcm(long long a,long long b){     
        if(a>b)
            return (a/gcd(a,b))*b;
        else
            return (b/gcd(a,b))*a;    
    } 
    
    int main()
    {
        long long int a ,b ;
        cin>>a>>b;
        cout<<lcm(a,b)<<endl;        
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题