- The Modern C++ Challenge
- Marius Bancila
- 181字
- 2021-06-25 22:01:23
2. Greatest common pisor
The greatest common pisor (gcd in short) of two or more non-zero integers, also known as the greatest common factor (gcf), highest common factor (hcf), greatest common measure (gcm), or highest common pisor, is the greatest positive integer that pides all of them. There are several ways the gcd could be computed; an efficient method is Euclid's algorithm. For two integers, the algorithm is:
gcd(a,0) = a
gcd(a,b) = gcd(b, a mod b)
This can be very simply implemented in C++ using a recursive function:
unsigned int gcd(unsigned int const a, unsigned int const b)
{
return b == 0 ? a : gcd(b, a % b);
}
A non-recursive implementation of Euclid's algorithm should look like this:
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 pisor of two numbers.
推薦閱讀
- Progressive Web Apps with React
- Visual Studio 2012 Cookbook
- 網(wǎng)頁(yè)設(shè)計(jì)與制作教程(HTML+CSS+JavaScript)(第2版)
- JavaScript+Vue+React全程實(shí)例
- CKA/CKAD應(yīng)試教程:從Docker到Kubernetes完全攻略
- JavaScript by Example
- Microsoft System Center Orchestrator 2012 R2 Essentials
- 區(qū)塊鏈底層設(shè)計(jì)Java實(shí)戰(zhàn)
- Julia for Data Science
- PHP 8從入門(mén)到精通(視頻教學(xué)版)
- PHP+MySQL Web應(yīng)用開(kāi)發(fā)教程
- MATLAB 2020 GUI程序設(shè)計(jì)從入門(mén)到精通
- Mastering Python
- Python全棧開(kāi)發(fā):數(shù)據(jù)分析
- MATLAB語(yǔ)言及編程實(shí)踐:生物數(shù)學(xué)模型應(yīng)用