思路是就是枚举最大公约数x0到最小公倍数y0之间的所有数,要满足下面两个条件
1、首先p q乘积 必须等于x0 * y0
2、p q的最大公约数等于 x0,最小公倍数等于y0
#include <iostream>
using namespace std;
inline int gcd(const int & a_,const int & b_)
{
int a ,b;
a = a_;
b = b_;
if(a < b)
{
a = a ^ b;
b = a ^ b;
a = a ^ b;
}
while(b)
{
int tem;
tem = b;
b = a % b;
a = tem;
}
return a;
}
inline int lcm(const int & a, const int &b)
{
int tem;
tem = (a* b) / gcd(a,b);
return tem;
}
int main()
{
int p,q,count,x0,y0;
cin>>x0>>y0;
count = 0;
for(p = x0; p <= y0; p++)
for(q = x0; q <= y0; q++)
{
if(p * q > x0 *y0)continue;
else if(p * q == x0 * y0)
{
if(gcd(p,q) == x0 && lcm(p,q) == y0)
{
//cout<<p<<" "<<q<<endl;
count++;
}
}
}
cout<<count;
return 0;
}
另外想了一下 其实还是有优化的余地的
#include <iostream>
using namespace std;
inline int gcd(const int & a_,const int & b_)
{
int a ,b;
a = a_;
b = b_;
if(a < b)
{
a = a ^ b;
b = a ^ b;
a = a ^ b;
}
while(b)
{
int tem;
tem = b;
b = a % b;
a = tem;
}
return a;
}
inline int lcm(const int & a, const int &b)
{
int tem;
tem = (a* b) / gcd(a,b);
return tem;
}
int main()
{
int p,q,count,x0,y0;
cin>>x0>>y0;
count = 0;
for(p = x0; p <= y0; p++)
{
if(p % x0 == 0)
{
q = x0 * y0 / p;
if(gcd(p,q) == x0 && lcm(p,q) == y0)
{
// cout<<p<<" "<<q<<endl;
count++;
}
}
}
cout<<count;
return 0;
}
只用一重循环就可以了
从下到上依次是第一个代码 和第二个代码 以及第二个代码 去掉inline后的运行截图
第二个代码 去掉inline后 运行了两次都是1ms 可能编译器的优化比这个inline还好些吧。
另外关于几种不用临时变量交换位置的代码 好像还有
a = a + b;
b = a - b;
a = a - b;
百度一下就知道了