A Simple Math Problem
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 1648 Accepted Submission(s): 470
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
1、优化
通过循环找一组解,在循环外面判断是不是最小公倍数
代码如下:
#include <cstdio>
#include <algorithm>
using namespace std;
int Judge(int x, int y, int b){
int i = x,j=y;
if(i < j)
swap(i,j);
while(j){
int temp = j;
j = i % j;
i = temp;
}
int num = x * y / i;
if(num == b)
return 1;
return 0;
}
int main(){
int a,b;
while(~scanf("%d%d",&a,&b)){
int flag = 0,x;
for(x = a/2; x > 0; x --){
if(b%x == 0 && b % (a-x) == 0){
flag = 1;
break;
}
}
if(flag && (Judge(x,a-x,b)))
printf("%d %d\n",x,a-x);
else
printf("No Solution\n");
}
return 0;
}
但是这种方法很悬,936ms差点超时。
2、正解公式推导
假设l为x,y的最大公约数即l=gcd(x,y);
x=i*l; y=j*l;
则 (i+j)*l=a; i*j*l=b;
由于i与j互质,则i*j与i+j互质;所以gcd(x,y)==l==gcd(,a,b);
代码如下:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
int main()
{
long long a,b;
while(~scanf("%lld%lld",&a,&b))
{
long long ll=__gcd(a,b);
a=a/ll;
b=b/ll;
if(a*a-4*b<0)
printf("No Solution\n");//判定一元二次方程误解
else
{
long long x=(a+sqrt(a*a-4*b))/2;//韦达定理
x*=ll;
long long y=a*ll-x;
if(x*y/__gcd(x,y)==b*ll)
printf("%lld %lld\n",y,x);
else
printf("No Solution\n"); //有解但是不满足最小公倍数
}
}
return 0;
}