A Simple Math Problem
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 1634 Accepted Submission(s): 460
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
mdzz
这个题 煞费脑筋- - 到结束没有退出gcd(x,y)==gcd(a,b); ╮(╯▽╰)╭ 还是数学不好
12w 数据 扫一遍 肯定超时; 一个for 也超时;
解题思路:
x+y= a;
lcm(x,y)=b; 即 x*y=b*gcd(x,y);
联立方程 有 x²-a*x+b*gcd(x,y)==0 解这个方程的 解就可以
现在推gcd(x,y)=gcd(a,b);
另gcd(x,y)= k;
得出 gcd(x,y)=gcd(a,b);
接着就是解 二元一次方程的问题
detal=a²-4*b*gcd(x,y);
detal<0 无解
大于零则 x=(a-sqrt(detal))/2 y=a-x; 注意 x要小于y 有两个解 只输出第一个 x<y的 并且要注意
sqrt(detal) 为整数才可以
#include<stdio.h>
#include<math.h>
/*
gcd(x,y)=gcd(a,b)
*/
int gcd(int x,int y)
{
if(y==0) return x;
else return gcd(y,x%y);
}
int main() {
int a,b;
int x,y,i,j;
int low,high;
while(~scanf("%d %d",&a,&b))
{
int k=gcd(a,b);
int detal=a*a-4*b*k;
if(detal<0)
{
printf("No Solution\n");
continue;
}
else
{
int s=sqrt(detal);
if(s*s!=detal||(a-s)%2!=0)
{
printf("No Solution\n");
continue;
}
x=(a-s)/2;
y=a-x;
x<y?x:y;
y=a-x;
printf("%d %d\n",x,y);
}
}
return 0;
}