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

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.

主站蜘蛛池模板: 泸溪县| 海林市| 仁寿县| 保靖县| 乐山市| 岢岚县| 浦北县| 韶山市| 金秀| 峡江县| 尖扎县| 神农架林区| 平陆县| 大田县| 龙川县| 霸州市| 嘉荫县| 濉溪县| 十堰市| 陈巴尔虎旗| 江陵县| 蒙城县| 响水县| 宁陵县| 沙坪坝区| 石屏县| 盐源县| 玛纳斯县| 凤山市| 德令哈市| 西昌市| 兴义市| 宁德市| 宜兰县| 南部县| 广元市| 芮城县| 建始县| 新乐市| 夏河县| 安徽省|