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 ( T
Output
Print the lowest integer B such that LCM(A, B) = 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;
}
本文介绍了一个关于数学算法的问题:已知两个整数A和它们的最小公倍数LCM,求解另一个整数B。通过分析算法流程,包括判断LCM是否为A的倍数、计算B的初值并利用最大公约数调整B值,直至找到符合条件的B。该问题涉及了算法设计、最大公约数与最小公倍数的概念。

641

被折叠的 条评论
为什么被折叠?



