Largest common factor on lens c

I am new to object c and I would like to know if there is a method for the greatest common factor

gcf() for example so you get the idea

+7
source share
4 answers

No function out of the box. Because Objective-C is a superset of C, you can grab an existing library or feature set and enable it where necessary.

Based on http://www.idevelopment.info/data/Programming/data_structures/c/gcd/gcd.c you can 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 this file when you want to use the gcd function:

 #import "gcd.h" 
+8
source

There is no built-in method, but the Euclidean algorithm is simple to implement and quite efficient.

The GCD binary algorithm may be a little more efficient. This link has a C code that implements it.

+4
source

Actually the most elegant solution I came across (non-recursive, of course):

 int gcd (int a, int b){ int c; while ( a != 0 ) { c = a; a = b%a; b = c; } return b; } 

Source

+3
source

Just enter damian86 into the Objective-C style (a reference to self suggests the context of the object, change it accordingly, you can make it a category, etc.):

 -(int)greatestCommonDivisorM:(int)m N:(int)n { int t, r; if (m < n) { t = m; m = n; n = t; } r = m % n; if (r == 0) { return n; } else { return [self greatestCommonDivisorM:n N:r]; } } 
0
source

All Articles