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

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.

主站蜘蛛池模板: 临泽县| 潞城市| 友谊县| 图片| 红桥区| 上犹县| 金坛市| 磐石市| 庄河市| 临潭县| 榆中县| 华蓥市| 饶阳县| 和田市| 兴安盟| 龙陵县| 积石山| 泸水县| 阳新县| 磐石市| 定南县| 浏阳市| 苏州市| 霍城县| 阳信县| 师宗县| 儋州市| 宁城县| 郑州市| 杨浦区| 珠海市| 湘潭县| 始兴县| 冷水江市| 西藏| 突泉县| 农安县| 博野县| 鄢陵县| 安宁市| 苗栗县|