2016 ICPC Dalian- A Simple Math Problem
[D - A Simple Math Problem 传送门](Problem - 5974 (hdu.edu.cn))
题面
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 (10^{12}) 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
,满足x + y = a
和lcm(x, y) = b
。
求解:
知识铺垫:
- 最大公倍数(gcd)和最小公因数(lcm)的关系:(a * b = gcd(a, b) * lcm(a,b))
- 一元二次方程系数与根的关系——韦达定理
看到(x + y = a)和(x * y = b),且a, b已知,如果x,y存在的话,那么一定会有一个一元二次方程(Ax^2+Bx+C=0),其解为x和y。
我们可以得到:
- (x+y=-frac{B}{A}=a) 和 (x*y=frac{C}{A}=b*gcd(a,b))
- 当x和y存在时一元二次方程的(Deltage0),推导可得到(Delta=B^2-4ACge0)即(frac{B^2}{A^2}ge4frac{C}{A})。带入之后得,当(a^2ge4b)时,x、y才有可能存在。
再进行如下数学推导,就能求出x和y了~
最终我们得到了X和Y的值,但是要注意,(sqrt{Delta})结果不一定是整数,所以最后需要带回去判断(X+Y=a)能否成立,输出答案即可
AC代码
#include<bits/stdc++.h>
using namespace std;
#define gcd(a, b) __gcd(a, b)
#define lcm(a, b) a * b / __gcd(a, b)
long long a, b;
int main(){
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
while(cin >> a >> b){
long long deta = a * a - 4 * b * gcd(a, b) ;
if(deta < 0 ) cout << "No Solution" << endl;
else{
long long m = (a - sqrt(deta)) / 2,
n = (a + sqrt(deta)) / 2;
if(n != a - m) cout << "No Solution" << endl;
else{
cout << m << ' ' << n << endl;
}
}
}
return 0;
}