Relatively Prime Numbers

て烟熏妆下的殇ゞ 提交于 2019-12-06 05:05:39

问题


How to make a function in c++ to determine if two entered numbers are relatively prime (no common factors)? For example "1, 3" would be valid, but "2, 4" wouldn't.


回答1:


Galvanised into action by Jim Clay's incautious comment, here is Euclid's algorithm in six lines of code:

bool RelativelyPrime (int a, int b) { // Assumes a, b > 0
  for ( ; ; ) {
    if (!(a %= b)) return b == 1 ;
    if (!(b %= a)) return a == 1 ;
  }
}

Updated to add: I have been out-obfuscated by this answer from Omnifarious, who programs the gcd function thus:

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));
}

So now we have a three-line version of RelativelyPrime:

bool RelativelyPrime (int a, int b) { // Assumes a, b > 0
   return (a<b) ? RelativelyPrime(b,a) : !(a%b) ? (b==1) : RelativelyPrime (b, a%b);
}



回答2:


One of the many algorithms for computing the Greatest Common Denominator.



来源:https://stackoverflow.com/questions/6444918/relatively-prime-numbers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!