UVa 11889 Benefit (数论)

11889 - Benefit

Time limit: 5.000 seconds

http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=467&page=show_problem&problem=2989

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  A  and  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和C的唯一素因子分解来求出尽可能小的B的唯一素因子分解,进而求出B,但是这种方法的复杂度是O(C)。

有没有更快的方法?

方法2:

由于

        AB/gcd(A,B)=C,

记C/A为B',则

        B=B'gcd(A,B),

        B=kB',

则有

        gcd(A,kB')=k,

如何求出k值呢?——通过不断“吸取”A中的A和B'的公约数来实现这一点,详见代码。

复杂度:O(log A)


完整代码:

/*0.055s*/

#include<cstdio>

int gcd(int a, int b)
{
	return b == 0 ? a : gcd(b, a % b);
}

int main(void)
{
	int T, a, b, c, d;
	scanf("%d", &T);
	while (T--)
	{
		scanf("%d%d", &a, &c);
		if (c % a)
			puts("NO SOLUTION");
		else
		{
			b = c / a;
			d = gcd(a, b);
			while (d != 1)
			{
				b *= d;
				a /= d;
				d = gcd(a, b);
			}
			printf("%d\n", b);
		}
	}
	return 0;
}




你可能感兴趣的:(C++,ACM,uva)