hdu 5974 A Simple Math Problem

本文介绍了解决一个特定数学问题的方法:给定两个正整数a和b,找到合适的X和Y使得X+Y=a且X和Y的最小公倍数等于b。文章提供了两种解决方案,一种是通过优化的遍历方法,另一种则是利用数学公式进行求解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

A Simple Math Problem

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 1648    Accepted Submission(s): 470


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


题意很好理解 ,大家都会遇到的问题就是超时,解决办法有两个

1、优化

通过循环找一组解,在循环外面判断是不是最小公倍数

代码如下:

#include <cstdio>
#include <algorithm>
using namespace std;

int Judge(int x, int y, int b){
    int i = x,j=y;
    if(i < j)
        swap(i,j);
    while(j){
        int temp = j;
        j = i % j;
        i = temp;
    }
    int num = x * y / i;
    if(num == b)
        return 1;
    return 0;
}
int main(){
    int a,b;
    while(~scanf("%d%d",&a,&b)){
        int flag = 0,x;
        for(x = a/2; x > 0; x --){
            if(b%x == 0 && b % (a-x) == 0){
                    flag = 1;
                    break;
            }
        }
        if(flag && (Judge(x,a-x,b)))
            printf("%d %d\n",x,a-x);
        else
            printf("No Solution\n");
    }
    return 0;
}

但是这种方法很悬,936ms差点超时。

2、正解公式推导

假设l为x,y的最大公约数即l=gcd(x,y);

x=i*l; y=j*l;

则 (i+j)*l=a; i*j*l=b;

由于i与j互质,则i*j与i+j互质;所以gcd(x,y)==l==gcd(,a,b);


代码如下:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;

int main()
{
    long long a,b;
    while(~scanf("%lld%lld",&a,&b))
    {
        long long ll=__gcd(a,b);
        a=a/ll;
        b=b/ll;
        if(a*a-4*b<0)
            printf("No Solution\n");//判定一元二次方程误解
        else
        {
            long long x=(a+sqrt(a*a-4*b))/2;//韦达定理
            x*=ll;
            long long y=a*ll-x;
            if(x*y/__gcd(x,y)==b*ll)
                printf("%lld %lld\n",y,x);
            else
                printf("No Solution\n");    //有解但是不满足最小公倍数
        }
    }
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值