UVa 11889 Benefit (枚举因子)

13 篇文章 0 订阅
10 篇文章 0 订阅

题目传送门

题意:输入一个T代表多组数据,输入A,C分别为LCM(A,B)=C,求所对应的最小的B,并且输出,否则输出“NO SOLUTION”;

题解:怎么想???刚开始想的是两个数直接除,显然是不行的,例如LCM(1,12)=12,LCM(2,12)=12,所以直接用C/A肯定是错误的;

还是乖乖一个一个遍历吧。将C一个一个分解,换来的却是TLE!

#include <iostream>//错误代码,超时!!!
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <string>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
using namespace std;
#define io ios::sync_with_stdio(0),cin.tie(0)
#define ms(arr) memset(arr,0,sizeof(arr))
#define inf 0x3f3f3f
typedef long long ll;
const int mod=1e9+7;
const int maxn=3e5+7;
int gcd(int a,int b)
{
    return b?gcd(b,a%b):a;
}
int main()
{
    int t;
    io;
    cin>>t;
    while(t--)
    {
        int a,c;
        cin>>a>>c;
        if(c%a==0)//遍历寻找。
        {
            for(int b=1;b<=c;b++)
            {
                if(a*b==c*gcd(a,b))
                {
                    cout<<b<<endl;
                    break;
                }
            }
        }
        else
        {
            cout<<"NO SOLUTION"<<endl;
        }
    }
    return 0;
}

改进一下,优化一下代码,减少循环次数。

#include <iostream>//AC代码
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <string>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
using namespace std;
#define io ios::sync_with_stdio(0),cin.tie(0)
#define ms(arr) memset(arr,0,sizeof(arr))
#define inf 0x3f3f3f
typedef long long ll;
const int mod=1e9+7;
const int maxn=3e5+7;
ll gcd(ll a,ll b)
{
    return b?gcd(b,a%b):a;
}
int main()
{
    ll t;
    io;
    cin>>t;
    while(t--)
    {
        ll a,c;
        cin>>a>>c;
        if(c%a==0)
        {
            ll num=c/a;
            for(ll b=num;b<=c;b+=num)//缩小循环的范围,有效缩短了遍历时间
            {
                if(b==num*gcd(a,b))
                {
                    cout<<b<<endl;
                    break;
                }
            }
        }
        else if(c%a!=0||a>c)//如果C%A!=0,或者A>C,显然不肯能存在这样的B
        {
            cout<<"NO SOLUTION"<<endl;
        }
    }
    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值