数学问题—Greatest common divisor

Greatest common divisor

Problem

写一个程序,给定两个正整数,计算并打印出最大公约数。

Solution

  • 最大公约数(greatest common divisor, gcd )就是两个或者多个非零整数的最大公因子,最大公因子就是能够同时整除这些非零整数的最大整数。
  • 实现求解最大公约数的算法有很多,其中一个有效的算法就是欧几里得算法(Euclid’s
    algorithm),同时《九章算术》里面的更相减损术也可以求解。
  • 根据欧几里得算法,可以使用递归的方式实现,也可以使用非递归的方式实现。Euclid’s algorithm 也称之为 辗转相除法:1. 当两个数相等时,其中任意一个就是它们的最大公约数,因为它们的余数为 0;2. 当两个数不相等时,用较大数除以较小数,当余数不为 0 时,这时使较小数作为被除数,余数作为除数,继续 2 的操作,直至余数为 0,也就是这两个数相等时,其中任一数为最大公约数。
  • 在 C++ 17 标准中已经有实现好的函数 std::gcd() ,可以直接使用;需要包含头文件 <numeric>

Code

github link
gitee link

/**
 * @file    : main.cpp
 * @brief   : Greatest common divisor
 * @author  : Wei Li
 * @date    : 2021-05-07
*/

#include <iostream>
#include <numeric> // C++ 17 std::gcd()

// recursive function
unsigned int gcd(unsigned int const a, unsigned int const b)
{
  return b == 0 ? a : gcd(b, a % b);
}

// non-recursive function
// unsigned int gcd(unsigned int a, unsigned int b)
// {
//   while (b != 0)
//   {
//     unsigned int r = a % b;
//     a = b;
//     b = r;
//   }
//   return a;
// }

// In C++17 there is a constexpr function called gcd() in the header <numeric> 
// that computes the greatest common divisor of two numbers.
// https://en.cppreference.com/w/cpp/numeric/gcd

int main(int argc, char** argv)
{
  unsigned int a = 0;
  unsigned int b = 0;
  std::cout << "Please input two positive integers: ";
  std::cin >> a >> b;

  std::cout << gcd(a, b) << std::endl;
  // C++ 17 <numeric>
  std::cout << std::gcd(a, b) << std::endl;
  
  return 0;
}

CMakeLists.txt

cmake_minimum_required(VERSION 3.10.0)
project(problem_02)

add_executable(problem_02 main.cpp)

Results

mkdir build
cd build
cmake .. -G "MinGW Makefiles"
mingw32-make
./problem_02.exe

// or using g++ command
g++ -std=c++17 -o problem_02 main.cpp

// ------------------------------------------------
// TEST
// $ ./problem_02.exe 
// Please input two positive integers: 256 64
// 64
// 64

// $ ./problem_02.exe 
// Please input two positive integers: 33 278
// 1
// 1

// $ ./problem_02.exe 
// Please input two positive integers: 3 99
// 3
// 3
// ------------------------------------------------

Reference

  • Book 《The Modern C++ Challenge》
  • Github
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值