HDU 5974 A Simple Math Problem(简单数学)

28 篇文章 0 订阅
4 篇文章 0 订阅

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,
若存在,输出x,y,否则输出“No Solution”。
注意:输出有顺序要求,必须是小值在前。

解题思路

某童鞋厉害得不行的直接看出了规律还是定理?
如果这两个值存在的话,就满足 gcd(x,y)=gcd(a,b),然后可得 x*y = lcm(x,y)*gcd(x,y)=gcd(x,y)*b=gcd(a,b)*b,再由完全平方公式可以得到 x 与 y 的差值,再与 x+y 相加减就可以得到 x,y,最后记得验证求得的值x+y=a,lcm(x,y)=b是否成立。
最后推一下这个规律还是定理?
设x=m*gcd(x,y),y=n*gcd(x,y);
gcd(a,b)=gcd(x+y,lcm(x,y))=gcd(m*gcd(x,y)+n*gcd(x,y),m*n*gcd(x,y))
              =gcd(x,y)*gcd(m+n,m*n);
因为 m,n 是互质的,所以 m+n 与 m*n 也是互质的,即可得gcd(x,y)=gcd(a,b)。

代码实现

#include <iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
#define ll long long
ll a,b;
ll gcd(ll a,ll b)
{
    if(b==0) return a;
    return gcd(b,a%b);
}
int main()
{
    while(~scanf("%lld %lld",&a,&b))
    {
        ll g=gcd(a,b);
        ll xy=b*g;
        ll z=a*a-4*xy;
        if(z<0)
        {
            printf("No Solution\n");
            continue;
        }
        else z=sqrt(z);
        ll x=(z+a)/2;
        ll y=a-x;
        if(x*y/gcd(x,y)!=b||x+y!=a)
            printf("No Solution\n");
        else
            printf("%lld %lld\n",y,x);
    }
    return 0;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值