官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 威海市| 什邡市| 平江县| 株洲市| 晋城| 沁源县| 习水县| 伊吾县| 淮滨县| 洮南市| 昭苏县| 云林县| 邳州市| 遵化市| 罗田县| 临海市| 额尔古纳市| 景德镇市| 寻甸| 八宿县| 明溪县| 晋州市| 高雄县| 习水县| 北宁市| 南皮县| 湖州市| 无锡市| 枣强县| 永泰县| 海安县| 霍山县| 民勤县| 曲水县| 奎屯市| 南充市| 五家渠市| 靖远县| 荥经县| 合阳县| 崇信县|