Given two positive integers a and b,find suitable X and Y to meet the conditions: X+Y=a Least Common Multiple (X, Y) =b
6 8 798 10780
Sample Output
No Solution
308 490
输入两个整数a,b,知否可以找到两个整数x,y.使其满足x+y=a,lcm(x,y)=b 如果找不到输出No Solution 否则输出x y(x<=y)
gcd(x,y)=gcd(a,b);
可以记住一个结论:a和b两个数,可以分解成x,y使得x+y=a,x和y的最小公倍数是b,(lcm(x,y)=b, 那么有gcd(a,b)=gcd(x,y);
#include <iostream>
#include <math.h>
using namespace std;
int gcd(int x,int y)
{
if(y==0)
return x;
else
return gcd(y,x%y);
}
int main()
{
int a,b,temp,k,d;
while(cin>>a>>b)
{
temp=gcd(a,b);
b*=temp;
k=a*a-4*b;
d=sqrt(k);
if(k<0||d*d!=k||(a+d)%2!=0)
{
cout<<"No Solution"<<endl;
continue;
}
d=(a+d)/2;
k=a-d;
if(d<=k)
cout<<d<<' '<<k<<endl;
else
cout<<k<<' '<<d<<endl;
}
return 0;
}