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

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.

主站蜘蛛池模板: 丰顺县| 池州市| 肥乡县| 公主岭市| 澳门| 巴塘县| 林周县| 上杭县| 重庆市| 临西县| 辽阳县| 邹平县| 洛浦县| 绍兴县| 高州市| 浦县| 来安县| 祁连县| 沁源县| 上林县| 汾西县| 天镇县| 镶黄旗| 勃利县| 钦州市| 高清| 玛纳斯县| 迁安市| 温泉县| 灵山县| 荥阳市| 区。| 屯留县| 错那县| 孟津县| 长阳| 拜城县| 吴忠市| 天等县| 大理市| 安徽省|