算法-欧几里得算法(辗转相除法)

介绍辗转相除法(欧几里德算法)原理及其C和C++语言实现,用于高效计算两个整数的最大公约数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

定理:gcd(a,b) = gcd(b,a mod b) (a>b 且a mod b 不为0)

gcd:greatest common divisor--最大公约数

mod:取余

a,b的最大公约数等于b与a对b取得余数的最大公约数。

c语言:

/*欧几里德算法:辗转求余
原理: gcd(a,b)=gcd(b,a mod b)
当b为0时,两数的最大公约数即为a
getchar()会接受前一个scanf的回车符
*/
#include<stdio.h>
unsigned int Gcd(unsigned int M,unsigned int N)
{
     unsigned int Rem;
     while(N > 0)
    {
       Rem = M % N;
       M = N;
       N = Rem;
    }
    return M;
}
int main(void)
{
    int a,b;
    scanf("%d %d",&a,&b);
    printf("the greatest common factor of %d and %d is ",a,b);
    printf("%d\n",Gcd(a,b));
    return 0;
}

c++:

#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);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值