0

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.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Shrusky
  • 3
  • 2

2 Answers2

2

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.
ankush__
  • 141
  • 9
0

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;
        
    }
    
    }
    
    
}

`

Shrusky
  • 3
  • 2
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 08 '22 at 16:52