Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relatively Prime Numbers

Tags:

c++

math

primes

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.

like image 963
Cobold Avatar asked Dec 07 '22 20:12

Cobold


2 Answers

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);
}
like image 160
TonyK Avatar answered Dec 24 '22 19:12

TonyK


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

like image 37
mikerobi Avatar answered Dec 24 '22 17:12

mikerobi