查找 GCD 和 LCM 为某些测试用例提供正确的输出,但我的提交显示错误的答案

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

我的查找 gcd 和 lcm 的 C++ 代码为某些测试用例提供了正确的输出,但我提交的内容显示了错误的答案。

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

是否缺少某些测试用例?或者我的代码有误。

在少数情况下它可能会失败:

  1. 当数字 xy 不适合 int 数据类型时。
  2. 如果 xy = 0 怎么办?
  3. 您正在做 product = a*b。这也可能导致溢出,导致 else 部分输出错误。

正确的代码如下:

`

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

`