greatest common divisor introduction to algorithm 3rd, example 31.2

本文详细介绍了C++语言中实现欧几里得算法和扩展欧几里得算法的过程,包括求最大公约数及扩展形式下的线性组合表达式。

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

算法导论 第三版 31.2

// greatest common divisor introduction to algorithm 3rd, example 31.2


#include <iostream>
#include <tuple>

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

std::tuple<int, int, int> gcd_ext(int a, int b)
{
    if (b == 0)
    {
        return std::make_tuple(a, 1, 0);
    }
    else
    {
        auto sr = gcd_ext(b, a%b);
        auto r = std::make_tuple<int, int, int>(std::move(std::get<0>(sr)), std::move(std::get<2>(sr)), std::get<1>(sr) - (int)std::floor(a/(double)b) * std::get<2>(sr));
        return r;
    }
}

void test_gcd(int a, int b)
{
    auto r = gcd(a, b);
    std::cout << "gcd(" << a << ',' << b << ") = " << r << std::endl;
}


void test_gcd_ext(int a, int b)
{
    auto  r = gcd_ext(a, b);
    std::cout << "gcd_ext(" << a << ',' << b << ") : " << std::get<0>(r) << " = (" << std::get<1>(r) << ") * " << a << " + (" << std::get<2>(r) << ") * " << b << std::endl;
}

int main()
{
    std::cout << "start" << std::endl;
    test_gcd(9, 3);
    test_gcd(-9, 3);
    test_gcd(9, -3);
    test_gcd(88, 64);
    test_gcd(7, 59);
    test_gcd(99, 78);
    test_gcd(78, 21);
    test_gcd(21, 15);
    test_gcd(15, 6);
    test_gcd(6, 3);
    test_gcd(3, 0);

    test_gcd_ext(9, 3);
    test_gcd_ext(7, 2);
    test_gcd_ext(-9, 3);
    test_gcd_ext(9, -3);
    test_gcd_ext(88, 64);
    test_gcd_ext(7, 59);
    test_gcd_ext(99, 78);
    test_gcd_ext(78, 21);
    test_gcd_ext(21, 15);
    test_gcd_ext(15, 6);
    test_gcd_ext(6, 3);
    test_gcd_ext(3, 0);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值