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=a、lcm(最小公倍数)(x,y)=b,求这样的x,y


思路:12w的测试数据,当然不能暴力。

首先肯定能想到x*y/gcd(x,y)==b;   {gcd(a,b)代表a,b的最大公约数}

设gcd(x,y)=t;

i*t = x;

j*t = y;

则i和j肯定互质;

所以i+j和i*j也肯定互质(下面会用到此规则,不明白为什么的,可记住该结论)

i*t + j*t = a;

i*j*t = b;

由i+j和i*j互质,所以gcd(a,b) = t;(解决该题的关键一波转换)

故i+j = a/t;

    i*j = b/t;

这马上联想到高中学的韦达定理;

构造二次函数t*x^2-a*t+b = 0;

用求根公式求出来即可得i , j; (取正根)

当然中间还有一些判别式的判定。

代码如下:



#include<stdio.h>
#include<string.h>
#include<iostream>
#include<math.h>

using namespace std;

int gcd(int a,int b)
{
    if(b==0)
        return a;
    return gcd(b,a%b);
}

int main()
{
    int a,b,t,x,y;
    while(~scanf("%d%d",&a,&b))
    {
        t = gcd(a,b);       //最大公约数
        if(a*a-4*t*b<0)  //判别式判断是否有根
            printf("No Solution\n");
        else
        {
            int i = ((a+sqrt(a*a-4*t*b))/(2*t));
            x = i*t;
            y = a-x;
            if(x*y/gcd(x,y)==b)  //判定解得的根是否正确
            {
                if(x<=y)
                    printf("%d %d\n",x,y);
                else
                    printf("%d %d\n",y,x);
            }
            else   
                printf("No Solution\n");
        }
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值