c++greatest-common-divisorlcm

Finding GCD and LCM giving correct output for some test cases but my submission shows wrong answer


My c++ code of finding gcd and lcm is giving correct output for some test cases but my submission shows wrong answer.

int T;
cin>>T;
int x,y,a,b;

while(T--)
{
    cin>>x>>y;
    a=(x>y)?x:y;  // a will be the greater number
    b=(y>x)?x:y;  // b will be the smaller number
    int product=a*b;
    
    ///we will find gcd, and lcm will be a*b/gcd
    
    if(a%b==0)
        cout<<b<<" "<<a<<endl;   // the smaller one will be gcd and the greater one, lcm
    else
    {
        int rem=a%b;
        
        while(rem!=0)
        {
            a=b;
            b=rem;
            rem=a%b;
        }
        cout<<b<<" "<<product/b<<endl;
    }
}

Are there certain test cases I am missing? Or maybe my code is wrong.


Solution

  • There are few cases on which it might fail:

    1. When numbers x and y are not able to fit in int data type.
    2. What if either x or y = 0?
    3. You are doing product = a*b. This also can lead to overflow resulting wrong output in else part.