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

321 views Asked by At

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.

2

There are 2 answers

0
ankush__ On BEST ANSWER

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.
1
Shrusky On

The correct code is as follows:

`

int T;
cin>>T;
long 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
    long int product=a*b;
    
    ///we will find gcd, and lcm will be a*b/gcd
    
    if(a==0 && b==0)
    {
        cout<<"0 0"<<endl;
    }
    
     else if(b==0)
    {
        cout<<a<<" 0"<<endl;
    }
    
    
    else
    {
        
    
    if(a%b==0)
    cout<<b<<" "<<a<<endl;   // the smaller one will be gcd and the greater one, lcm
    
    else
    {
        int rem=b;
        
        while(a%b!=0)
        {
            rem=a%b;
            a=b;
            b=rem;
        
            
            
        }
        cout<<rem<<" "<<product/b<<endl;
        
    }
    
    }
    
    
}

`