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
题解:
本题要求的是给定两个数a,b;让你求出
x+y=a&&lcm(x,y)=b;如果可以找到输出x,y;如果没有输出No Solution;
我们可以理解为lcm(x,y)=x*y/gcd(x,y)=b;
从而可以化简出下面的一元二次方程;
x⋅y=b⋅gcd(x,y)
x+y=a
↓
x⋅(a−x)=b⋅gcd(x,y)
↓
x2−ax+b⋅gcd(x,y)=0 这个式子里含有gcd(x,y),但是x,y是未知的,需要替换;
g=gcd(x,y);
回归本质;我们可以假设 x=k1*g y=k2*g;
g是二者的最大公约数,则k1和k2必然是两个互质的数;
然而 x+y=a x*y/g=b;
则 k1*g+k2*g=a k1*k2*g=b;
则 k1+k2=a/g k1*k2=b/g;
因为 k1,k2 互质 所以 k1+k2与k1*k2也是互质的
等同于 a/g 与 b/g也是互质的;
那么g就是a,b的最大公因数
也就是gcd(a,b)=gcd(x,y)
所以该题目转变成
求解一元二次方程 x2−ax+b⋅gcd(a,b)=0
下面给出该结论的互质证明:
p,q是互质的两个整数
M=p+q,N=pq
假设M,N不是互质的
那么必有M=aN或 N=aM a为整数
我们以M=aN为例,则原式等于 p+q=apq p=q(ap−1) p/q=ap−1
因为p,q互质所以p/q一定不会得到整数
但是a是整数,p是整数,则ap-1是整数
所以等式两边相矛盾故:若p,q是互质的,那么p+q和pq也是互质的
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
int a,b;
while(~scanf("%d %d",&a,&b))
{
int diat=a*a-4*b*__gcd(a,b);
if(diat<0)
{
printf("No Solution\n");
}
else
{
int p=sqrt(diat);
int sum=p*p;
if(sum!=diat)
{
printf("No Solution\n");
}
else
{
int x1=(a+p)/2;
int x2=(a-p)/2;
int x=min(x1,x2);
printf("%d %d\n",x,a-x);
}
}
}
return 0;
}