HDU-5974-A Simple Math Problem

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

題意:
已知 a,b,找出一個x 和 y 滿足 x+y=a,Lcm(x,y)=b;

思路(上網查找):
看數據範圍肯定不能進行暴力枚舉了!
令gcd(x,y) = g;
那麼
g * k1 = x;
g * k2 = y;
因爲g 是最大公約數,那麼k1與k2 必互質!
=> g*k1*k2 = b
=> g*k1 + g * k2 = a;
所以k1 * k2 = b / g;
k1 + k2 = a/g;
因爲k1與k2 互質!
所以k1 * k2 和 k1 + k2 也一定互質(一個新學的知識點= = )
所以a/g 與b/g也互質!
那麼g 就是gcd(a,b);
所以我們得出一個結論: gcd(x,y) == gcd(a,b);;
所以x + y 與 x * y都是已知的了,解一元二次方程即可!

因爲 gcd(a,b) * lcm(a,b) = a*b;
所以 lcm(a,b) = a/gcd(a,b)*b;
所以題目條件可化爲一個一元二次方程:x*x-a*x+b*gcd(a,b)。

代碼

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
using namespace std;
int a,b;
int gcd(int m,int n)
{
    if(n == 0)
        return m;
    else
        return gcd(n,m%n);
}
int main()
{
    int m,p,l;
    int q;
    int x1,x2;
    int flag;
    while(scanf("%d%d",&a,&b)!=EOF)
    {
        flag = 1;
        m = gcd(a,b);
        p = a*a-4*b*m;  //解一元二次方程
        if(p < 0)  //無解
        {
            printf("No Solution\n");
            continue;
        }
        q = (int)sqrt(p);
        if(q*q != p)//是否爲整數
            flag = 0;
        x1 = (a+q)/2;
        x2 = (a-q)/2;
        if(flag == 0)
            printf("No Solution\n");
        else
        {
            l = min(x1,x2);
            printf("%d %d\n",l,a-l);
        }
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章