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.
Asked
Active
Viewed 1.2k times
4
-
4[The Euclidean Algorithm](http://en.wikipedia.org/wiki/Euclidean_algorithm) – Ismail Badawi Jun 22 '11 at 18:49
-
2see Stein's Algorithm or Binary GCD. And, homework. – Erik Olson Jun 22 '11 at 18:54
2 Answers
10
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);
}
-
5
-
1+1 for horrible code style - it honors Euclid. Any simple, clear explanation of how it works is missing the pure genius of the astonishing theorem. – DaveWalley Aug 14 '14 at 20:31
5
One of the many algorithms for computing the Greatest Common Denominator.

mikerobi
- 20,527
- 5
- 46
- 42
-
As referenced in that Wikipedia article under "Further Reading", Knuth's AOCP v.2 (Seminumerical Algorithms) has good analysis of the efficiency of several approaches. – hardmath Jun 23 '11 at 13:01