bi_jia_ming @ 2024-12-20 20:57:56
3个TLE
请问如何优化?
玄关!
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <cstring>
#include <string>
#include <cmath>
using namespace std;
int gcd(int n,int m)
{
while(m!=0)
{
int temp=m;
m=n%m;
n=temp;
}
return n;
}
int lcm(int n,int m)
{
return (n*m)/gcd(n,m);
}
int main()
{
int n,m,ans=0;
cin>>n>>m;
for(int i=n;i*i<=m;i++)
{
for(int j=n;j*j<=m;j++)
{
if(gcd(i,j)==n && lcm(i,j)==m)
{
ans+=2;
}
}
}
cout<<ans;
return 0;
}
by bi_jia_ming @ 2024-12-20 21:00:37
大佬们对不起,代码发错了。 如下:
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <cstring>
#include <string>
#include <cmath>
using namespace std;
int gcd(int n,int m)
{
while(m!=0)
{
int temp=m;
m=n%m;
n=temp;
}
return n;
}
int lcm(int n,int m)
{
return (n*m)/gcd(n,m);
}
int main()
{
int n,m,ans=0;
cin>>n>>m;
for(int i=n;i<=m;i++)
{
for(int j=n;j<=m;j++)
{
if(gcd(i,j)==n && lcm(i,j)==m)
{
ans++;
}
}
}
cout<<ans;
return 0;
}
by bi_jia_ming @ 2024-12-20 21:03:22
gcd函数利用了辗转相除法求出了最大公因数,lcm函数用了gcd函数求出了最小公倍数,但本蒟蒻不知如何优化,还望大佬指导。
by long_long_2014 @ 2024-12-21 15:31:42
@bi_jia_ming
#include<iostream>
#include<math.h>
using namespace std;
int gcd1(int a1,int b1)
{
int r;
if(a1<b1)
swap(a1,b1);
while(a1%b1!=0)
{
r=a1%b1;
a1=b1;
b1=r;
}
return b1;
}
int main()
{
int a,b,c,i,j,p,q,sum;
cin>>a>>b;
sum=0;
if (a>b)
swap(a,b);
if (b%a==0)
{
c=b/a;
for(i=1;i<=c;i++)
{
if(c%i==0)
{
p=i;
q=c/i;
j=gcd1(p,q);
if(j==1)
sum++;
}
}
}
cout<<sum<<endl;
return 0;
}
by bi_jia_ming @ 2024-12-26 14:39:22
谢谢大佬,已关!
by long_long_2014 @ 2024-12-27 09:51:55
其实我也是五年级的
by bi_jia_ming @ 2024-12-27 13:50:50
......