Loading

2016 ICPC Dalian- A Simple Math Problem

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 = alcm(x, y) = b

求解:

知识铺垫:

  1. 最大公倍数(gcd)和最小公因数(lcm)的关系:\(a * b = gcd(a, b) * lcm(a,b)\)
  2. 一元二次方程系数与根的关系——韦达定理

看到\(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存在时一元二次方程的\(\Delta\ge0\),推导可得到\(\Delta=B^2-4AC\ge0\)\(\frac{B^2}{A^2}\ge4\frac{C}{A}\)。带入之后得,当\(a^2\ge4b\)时,x、y才有可能存在

再进行如下数学推导,就能求出x和y了~

\[将B=-Aa,C=Ab代入 Ax^2+Bx+c=0,得: \\Ax^2-Aax+Ab*gcd(a,b)=0,化简后得: \\x^2-ax+b*gcd(a,b)=0,\Delta=a^2-4b*gcd(a,b) \\由一元二次方程求根公式得:X=\frac{a-\sqrt{a^2-4b*gcd(a,b)}}{2},Y=\frac{a+\sqrt{a^2-4b*gcd(a,b)}}{2} \]

最终我们得到了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;
}
posted @ 2021-01-29 19:47  Frank_Ou  阅读(85)  评论(0编辑  收藏  举报