Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

greatest common factor on objective c

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

like image 258
VenDiaS Avatar asked Mar 11 '11 23:03

VenDiaS


2 Answers

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"
like image 151
dianovich Avatar answered Sep 28 '22 13:09

dianovich


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.

like image 29
wnoise Avatar answered Sep 28 '22 13:09

wnoise