求两数的最大公约数--gcd函数

C++模板:

__gcd(x,y);
int、long long类型都可以,需要注意的是两个类型必须要相同,还有不能用浮点型,当然手写gcd函数也是可以的,它头文件是algorithm。

#include<bits/stdc++.h>
#include <iostream>
#include <algorithm>
using namespace std;
int a,b;

int main()
{
 cin >> a >> b;
 cout << __gcd(a,b) << endl;
 return 0;
}

 

手动实现:方便修改数的类型

1、递归实现:

int gcd(int a,int b)
{
    if(b == 0)
        return a;
    return gcd(b,a%b);
}

2、非递归实现:

int gcd(int a,int b)
{
    while(b){
        int t = b;
        b = a%b;
        a = t;
    }
    return a;
} 

 

posted @ 2020-10-21 14:52  neverstopcoding  阅读(325)  评论(0编辑  收藏  举报