题目A Simple Math Problem

题目链接:https://vjudge.net/problem/HDU-5974

题目大意:

给出a,b两数,求解x,y  ,并符合 x + y = a , lcm ( x , y ) = b。

思路:

数据过大,暴力必超时。此时可设gcd( x , y ) = g,则有g * k1 = x,g * k2 = y;

所以有g * k1 + g * k2 = a,g * k1 * k2 = b,即(k1 + k2) =  a / g,k1 * k2 = b / g;

因为(k1 + k2)与  k1 * k2 互质,所以gcd( a, b ) = g,得到 g 的值后便可通过求解k1,k2求得答案。

解题代码:

 1 #include <cstdio>
 2 #include <iostream>
 3 #include <algorithm>
 4 #include <cmath>
 5 #include <string>
 6 #include <cstring>
 7 #include <map>
 8 using namespace std;
 9 const long long N = 1e9 + 7;
10 typedef long long ll;
11 
12 ll gcd(ll a, ll b)
13 {
14     return b > 0 ? gcd(b,a%b) : a;
15 }
16 int main()
17 {
18     ll a,b;
19     while(~scanf("%lld%lld",&a,&b))
20     {
21         ll g = gcd(a,b);
22         ll k1,k2;
23         ll q = a*a - 4 * g * b;
24         if(q < 0)              //判断方程是否有解
25             cout << "No Solution" << endl;
26         else
27         {
28 
29             ll m = sqrt(q);
30             if(m * m != q)
31                 cout << "No Solution" << endl;
32             else
33             {
34                 ll a1 = a+m;
35                 ll a2 = a-m;
36                 if(a1 & 1 || a2 & 1)
37                 {
38                     cout << "No Solution" << endl;
39                 }
40                 else
41                 {
42                     cout << min(a1/2,a2/2) << " " << max(a1/2,a2/2)  << endl;
43                 }
44             }
45 
46         }
47     }
48     return 0;
49 }