I'm new to objective c and I would like to know if there is a method for greatest common factor
gcf()
for example so you get the idea
There's no out of the box function. Since Objective-C is a superset of C, you can grab an existing library or set of functions and include it where necessary.
Based on http://www.idevelopment.info/data/Programming/data_structures/c/gcd/gcd.c, you might do this:
// gcd.h
int gcd(int m, int n);
// gcd.c
int gcd(int m, int n) {
int t, r;
if (m < n) {
t = m;
m = n;
n = t;
}
r = m % n;
if (r == 0) {
return n;
} else {
return gcd(n, r);
}
}
Include that file whenever you should wish to use the gcd
function:
#import "gcd.h"
There is no built in method, but the Euclidean algorithm is easy to implement, and quite efficient.
The binary GCD algorithm can be slightly more efficient. This link has C code implementing it.
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