如何在c++中创建一个函数来确定两个输入的数字是否互质(没有公因数)?
例如,“1, 3”有效,但“2, 4”无效。
吉姆·克莱 (Jim Clay) 的不谨慎评论促使其付诸行动,以下是六行代码的欧几里得算法:
bool RelativelyPrime (int a, int b) { // Assumes a, b > 0
for ( ; ; ) {
if (!(a %= b)) return b == 1 ;
if (!(b %= a)) return a == 1 ;
}
}
Updated补充:我已经被迷惑了这个答案来自 Omnifarious https://stackoverflow.com/questions/6016771/is-constexpr-really-needed/6476038#6476038,谁编程gcd
函数如下:
constexpr unsigned int gcd(unsigned int const a, unsigned int const b)
{
return (a < b) ? gcd(b, a) : ((a % b == 0) ? b : gcd(b, a % b));
}
现在我们有了一个三行版本的relative prime:
bool RelativelyPrime (int a, int b) { // Assumes a, b > 0
return (a<b) ? RelativelyPrime(b,a) : !(a%b) ? (b==1) : RelativelyPrime (b, a%b);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)