A Simple Math Problem
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 3965 Accepted Submission(s): 1221
Problem Description
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
Input
Input includes multiple sets of test data.Each test data occupies one line,including two positive integers a(1≤a≤2*10^4),b(1≤b≤10^9),and their meanings are shown in the description.Contains most of the 12W test cases.
Output
For each set of input data,output a line of two integers,representing X, Y.If you cannot find such X and Y,output one line of "No Solution"(without quotation).
Sample Input
6 8 798 10780
Sample Output
No Solution 308 490
Source
Recommend
wange2014
在这道题中只要能想到 gcd(a,b)=c=gcd(x,y) 那么这个问题就很好解了 接下来我写一下推导过程
x+y=a, x*y/gcd(x,y)=b
令 gcd(x,y)=c 、x=i*c y=j*c
i*c+j*c=a ,c*i*j=b c*(i+j)=a ,
c*i*j=b因为 i j 互质 所以 gcd(a,b)=c=gcd(x,y)
所以一开始就能得到 c 值,
剩下就是求根i+j=a/c ,i*j=b/c
i+b/(c*i)=a/c ,c*i2-a*i+b=0最后得到 c*i2-a*i+b=0
也就是 gcd(a,b)*i*i-a*i+b=0 那么就有一个二元一次方程 通过方程求出 i j 最后求出 x y 进而得出结论
下面附上代码
#include<map>
#include<stack>
#include<math.h>
#include<string>
#include<vector>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define pi acos(-1)
using namespace std;
typedef long long ll;
const int MAX_N=100000+50;
const int INF=0x3f3f3f3f;
ll gcd(ll a, ll b)
{
return b==0?a:gcd(b,a%b);
}
int main()
{
ios::sync_with_stdio(false);
ll a,b;
while(cin>>a>>b)
{
ll c = gcd(a,b);
ll d = a*a-4*c*b;
if(d < 0) cout<<"No Solution"<<endl;
else
{
ll i = (a-sqrt(d))/2/c;
ll j = a/c - i;
ll x = i * c;
ll y = j * c;
if(x*y/c == b) cout<<x<<" "<<y<<endl;
else cout<<"No Solution"<<endl;
}
}
return 0;
}