相对素数

Relatively Prime Numbers

本文关键字:相对      更新时间:2023-10-16

如何在c++中生成一个函数,以确定输入的两个数字是否相对素数(没有公共因子)?例如,"1,3"是有效的,但"2,4"则无效。

由于Jim Clay不小心的评论,Euclid的算法有六行代码:

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

更新添加:Omnifarious的回答让我感到困惑,他对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));
}

现在我们有了一个三行版本的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);
}

计算最大公分母的众多算法之一。