- 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.
推薦閱讀
- Deploying Node.js
- Computer Vision for the Web
- Building Modern Web Applications Using Angular
- DevOps for Networking
- C/C++常用算法手冊(第3版)
- Podman實戰
- Microsoft System Center Orchestrator 2012 R2 Essentials
- Kali Linux Wireless Penetration Testing Beginner's Guide(Third Edition)
- 程序員修煉之道:通向務實的最高境界(第2版)
- 青少年學Python(第1冊)
- GitHub入門與實踐
- 量子計算機編程:從入門到實踐
- Implementing Domain:Specific Languages with Xtext and Xtend
- jQuery Essentials
- Flutter for Beginners