标签:
使用 “辗转相除法” 计算2个数的最大公因数:
1 int GCD_2(int nNum1, int nNum2) 2 { 3 if (nNum1 > nNum2) 4 { 5 nNum1 = nNum1 ^ nNum2; 6 nNum2 = nNum1 ^ nNum2; 7 nNum1 = nNum1 ^ nNum2; 8 } 9 if (nNum1 == 0) 10 { 11 return nNum2; 12 } 13 return GCD_2(nNum2 % nNum1, nNum1); 14 }
遍历 vector ,迭代 GCD_2 ,计算N个数的最大公因数:
1 int GCD_N(std::vector<int> vecNums) 2 { 3 int nRes = vecNums[0]; 4 std::for_each(vecNums.begin() + 1, vecNums.end(), 5 [&nRes](int x){ nRes = GCD_2(nRes, x); }); 6 return nRes; 7 }
测试:
1 int main() 2 { 3 int nArr[] = { 75, 45, 315 }; 4 std::vector<int> vecNums(nArr, nArr + sizeof(nArr) / 4); 5 int nRes = GCD_N(vecNums); 6 std::cout << nRes << std::endl; 7 return 0; 8 }
结果:
1 15
标签:
原文地址:http://www.cnblogs.com/Chameleon/p/4298623.html