[英]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.我的 c++ 查找 gcd 和 lcm 的代码为某些测试用例提供了正确的 output 但我提交的答案显示错误。
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.
或者也许我的代码是错误的。
There are few cases on which it might fail:在少数情况下它可能会失败:
x
and y
are not able to fit in int
data type.x
和y
不适合int
数据类型时。x
or y
= 0?x
或y
= 0 会怎样?product = a*b
.product = a*b
。 This also can lead to overflow resulting wrong output in else
part.else
部分。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;
}
}
}
` `
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.