题意:输入一个T代表多组数据,输入A,C分别为LCM(A,B)=C,求所对应的最小的B,并且输出,否则输出“NO SOLUTION”;
题解:怎么想???刚开始想的是两个数直接除,显然是不行的,例如LCM(1,12)=12,LCM(2,12)=12,所以直接用C/A肯定是错误的;
还是乖乖一个一个遍历吧。将C一个一个分解,换来的却是TLE!
#include <iostream>//错误代码,超时!!!
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <string>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
using namespace std;
#define io ios::sync_with_stdio(0),cin.tie(0)
#define ms(arr) memset(arr,0,sizeof(arr))
#define inf 0x3f3f3f
typedef long long ll;
const int mod=1e9+7;
const int maxn=3e5+7;
int gcd(int a,int b)
{
return b?gcd(b,a%b):a;
}
int main()
{
int t;
io;
cin>>t;
while(t--)
{
int a,c;
cin>>a>>c;
if(c%a==0)//遍历寻找。
{
for(int b=1;b<=c;b++)
{
if(a*b==c*gcd(a,b))
{
cout<<b<<endl;
break;
}
}
}
else
{
cout<<"NO SOLUTION"<<endl;
}
}
return 0;
}
改进一下,优化一下代码,减少循环次数。
#include <iostream>//AC代码
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <string>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
using namespace std;
#define io ios::sync_with_stdio(0),cin.tie(0)
#define ms(arr) memset(arr,0,sizeof(arr))
#define inf 0x3f3f3f
typedef long long ll;
const int mod=1e9+7;
const int maxn=3e5+7;
ll gcd(ll a,ll b)
{
return b?gcd(b,a%b):a;
}
int main()
{
ll t;
io;
cin>>t;
while(t--)
{
ll a,c;
cin>>a>>c;
if(c%a==0)
{
ll num=c/a;
for(ll b=num;b<=c;b+=num)//缩小循环的范围,有效缩短了遍历时间
{
if(b==num*gcd(a,b))
{
cout<<b<<endl;
break;
}
}
}
else if(c%a!=0||a>c)//如果C%A!=0,或者A>C,显然不肯能存在这样的B
{
cout<<"NO SOLUTION"<<endl;
}
}
return 0;
}