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.

Input 

The first line begin with an integer T ( T100000), the number of tests. Each test that comes in a separate line contains two integers Aand C ( 1AC107).

Output 

Print the lowest integer B such that LCM(AB) = C in a single line. If no such integer exists, print " NO SOLUTION" instead. (Quotes for clarity)

Sample Input 

3
2 6
32 1760
7 16

Sample Output 

3
55
NO SOLUTION

题目给出两个数A和B的最小公倍数LCM(A,B),以及其中一个数A,求另一个数B,

首先,最小公倍数肯定是A和B的倍数,所以只有LCM%A==0时,才是有意义的,然后,考虑两个互质的数,他们的最大公约数为1,最小公倍数为俩数的乘积,即LCM/A=B,

也就是说,先要将B=LCM/A,然后再计算G=GCD(A,B)是否为1,如果不为1,说明A,B两数不是互质的,那么就让B=B*G,A=A/G,最终如果G==1,那么B就是所求的值,这里还有一个求最大公约数的算法,只有一个return的递归,感觉不错,虽然速度一般,但对于提高写代码的速度很有帮助             



#include<iostream>
using namespace std;
typedef long long ll;
ll gcd(ll a,ll b )
{
	return b==0?a:gcd(b,a%b);
}

int main()
{
	int T;
	ll a,b,lcm,g;
	cin>>T;
	while(T--)
	{
		cin>>a>>lcm;
		if(lcm%a!=0)
		cout<<"NO SOLUTION"<<endl;
		else
		{
			b=lcm/a;
			while(g=gcd(a,b)&&g!=1)
			{
				b=b*g;
				a=a/g;
			}
			cout<<b<<endl;
		}
		
	}
	return 0;
}



你可能感兴趣的:(uva,benefit,11889)