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.
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);
}
One of the many algorithms for computing the Greatest Common Denominator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With