C++的标准库中提供了一些实用的函数,比如:

__gcd(x,y)函数
用于求x,y的最大公约数。x,y不能是浮点数
头文件:#include< algorithm>

用法:

#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
    int a,b;
    cin>>a>>b;
    cout<<__gcd(a,b)<<endl;
}

朴素实现方法:

算法的本质辗转相除

1.普通循环

int gcd(int a,int b) {
    int r;
    while (a%b!=0)
    {
        r=a%b;
        a=b;
        b=r;    
    }
    return b; 
}

2.递归+三元运算符

int gcd(int a,int b) {
    return b>0 ? gcd(b,a%b):a;
}

3.递归+ if 语句

求x 和 y 的最大公约数,就是求 y 和 x % y 的最大公约数

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

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐