UVA 11889-Benefit

Recently Yaghoub is playing a new trick to sell some more. When somebody gives him A Tomans, he who never has appropriate changes, asks for B Tomans such that lowest common multiple of A and B equals to C and he will pay back a round bill. Or otherwise take some snack instead of the remaining of his money. He believes that finding such a number is hard enough that dissuades students from paying that.

You should write a program that help poor students giving the appropriate amount of money to Yaghoub. Of course if there are several answers you go for students' benefit which is the lowest of them.


题目的意思就是给你A,C。让你求B,满足LCM(A,B)=C。让B尽量小。


思路:令k为AB的最小公倍数,x=A/k,y=B/k.

那么A=kx,B=ky.C=kxy;

k可以求出来的。

从1开始枚举y的值,是从小到大开始枚举。然后满足条件就跳出。输出答案即可。


这道题有一个非常坑的地方(其实是自己太不细心了),在判断的时候,相乘会超出int范围。


#include<stdio.h>
#include<math.h>
#include<algorithm>
using namespace std;
int main()
{
    int tt;
    scanf("%d",&tt);
    while(tt--)
    {
        int n,m;
        scanf("%d%d",&n,&m);
        if(m%n!=0)
        {
            puts("NO SOLUTION");
            continue;
        }
        int k=m/n;
        int f=1;
        for(int i=1;i<=n;i++)
        {
            if(!f) break;
            if(n%i==0)
            {
                int t=k*i;
                if((long long)__gcd(t,n)*m==(long long)n*t)//就是这里错了多次。
                {
                    printf("%d\n",t);
                    f=0;
                    break;
                }
            }
        }
    }
    return 0;
}


你可能感兴趣的:(UVA 11889-Benefit)