算法导论 第三版 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;
}