wikioi1012 最大公约数和最小公倍数问题之枚举

题目

思路是就是枚举最大公约数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;

百度一下就知道了


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值