A Simple Math Problem
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 456 Accepted Submission(s): 179
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
题意:意思很简单,给你a和b,问能否找出两个数x,y,符合x+y=a,lcm(x,y)=b。
思路:其实就是一道公式题。。设k=gcd(x,y),a=k(x+y),b=kxy,很明显gcd(a,b)=k(下面会给出证明),所以x+y=a/k,xy=b/k,然后就是解二元一次方程,直接套公式就可以得到。然后这道题没说清楚,输出的时候x要比y小,不然是过不了的。下面给代码:
关于gcd(x+y,lcm(x,y))==gcd(x,y)==g的证明
令
x=g*k1;
y=g*k2
易知gcd(k1,k2)==1
所以x+y==g*(k1+k2) lcm(x,y)==g*k1*k2
那么gcd(x+y,lcm(x,y))==gcd(g*(k1+k2),g*k1*k2)
要证明gcd(g*(k1+k2),g*k1*k2)==g 等价于证明gcd(k1+k2,k1*k2)==1
我们知道 a,b互质的时候 gcd(a+b,a*b)肯定是互质的,因为a+b的质因数肯定不包含a和b。
a*b的质因数肯定只包含a和b。
那么gcd(a+b,a*b)==1
因为k1,k2是互质的,所以gcd(k1+k2,k1*k2)==1
所以gcd(g*(k1+k2),g*k1*k2)==g
又因为gcd(x,y)==gcd(g*k1,g*k2)==g
所以gcd(x,y)==gcd(g*(k1+k2),g*k1*k2)==gcd(x+y,lcm(x,y))==g
得证
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
#include<cmath>
typedef long long LL;
using namespace std;
#define maxn 1005
#define ll l,mid,now<<1
#define rr mid+1,r,now<<1|1
#define lson l1,mid,l2,r2,now<<1
#define rson mid+1,r1,l2,r2,now<<1|1
LL gcd(LL a, LL b){
return !b ? a : gcd(b, a%b);
}
int main(){
LL a, b;
while (~scanf("%lld%lld", &a, &b)){
LL k = gcd(a, b);
LL num = a*a - 4 * b*k;
LL sqnum = sqrt(num);
//cout << num << endl << sqnum << endl;
LL x1 = a - sqnum;
LL x2 = a + sqnum;
if (sqnum*sqnum != num || x1 % (k << 1) || x2 % (k << 1)){
printf("No Solution\n");
}
else{
printf("%lld %lld\n", k*x1 / (k << 1), k*x2 / (k << 1));
}
}
}