zoukankan      html  css  js  c++  java
  • 欧几里得求最大公约数和最小公倍数

    欧几里得算法,据说是辗转相除法,然而我用的是更相减损术。。。

    嗯,自己的代码如下:

    //求最大公约数——欧几里得算法;最小公倍数—— 
    #include<iostream>
    using namespace std;
    int main()
    {
        int a,b,c,temp,A,B;
        while(cin>>a>>b)
        {
            A=a;B=b;
            if(a<b)
            {
                temp=a;
                a=b;
                b=temp;        
            }
            c=a-b;
            while(b!=c) 
            {
                if(b<c)
                    a=c;        
                else
                {
                    a=b;
                    b=c;
                }
                c=a-b;        
            }
            cout<<c<<" "<<A/c*B<<endl;        
        }
    
        return 0;
    }

    都是高中学过了的,确实没什么难度,但是看到别人的代码后顿时整个人都不好了。。

    #include <algorithm> // std::swap for c++ before c++11
    #include <utility> // std::swap for c++ since c++11
    int gcd(int a,int b)
    {
        if (a < b)
            std::swap(a, b);
        return b == 0 ? a : gcd(b, a % b);
    }

    人家的递归,人家的函数调用,学习了。。。

    偶尔玩玩C语言也是收获不小啊~~~

    #include<stdio.h>
    using namespace std;
    int gcd(int x,int y)
    {
        if(x<y)
        {
            int t=x;
            x=y;
            y=t;
        }
        return !y ? x : gcd(y,x%y);
    }
    int main()
    {
        int x,y;
        while(scanf("%d%d",&x,&y)!=EOF)
        {
                printf("%d %d
    ",gcd(x,y),x/gcd(x,y)*y);
        }
    }
  • 相关阅读:
    第二章整理
    汇编实验二
    汇编实验一
    第一章整理
    第一部分 | 第1章 —— Hello Cocos2d-x
    返回 *this 的成员函数以及 const重载
    C++中的const
    680. Valid Palindrome II
    字典树
    单调队列
  • 原文地址:https://www.cnblogs.com/fengyanlover/p/5049337.html
Copyright © 2011-2022 走看看