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;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章