Created
April 29, 2012 20:12
-
-
Save mayoff/2553024 to your computer and use it in GitHub Desktop.
reduced fractions in objective-c
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation/Foundation.h> | |
int gcd(int a, int b) { | |
// assumes a >= 0 && b > 0 | |
while (b != 0) { | |
int t = a % b; | |
a = b; | |
b = t; | |
} | |
return a; | |
} | |
NSString *stringByReducingFraction(int a, int b) { | |
if (a == 0) return @"0"; | |
if (a == b) return @"1"; | |
int g = gcd(a, b); | |
return [NSString stringWithFormat:@"%d/%d", a / g, b / g]; | |
} | |
int main(int argc, const char * argv[]) | |
{ | |
@autoreleasepool { | |
NSMutableArray *fractionArray = [[NSMutableArray alloc] init]; | |
for (int frac = 0; frac <= 15; ++frac) { | |
NSString *fracString = stringByReducingFraction(frac, 16); | |
[fractionArray addObject:fracString]; | |
} | |
NSLog(@"fractionArray = %@", fractionArray); | |
} | |
return 0; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
2012-04-29 15:11:35.488 reducedFraction[79098:403] fractionArray = ( | |
0, | |
"1/16", | |
"1/8", | |
"3/16", | |
"1/4", | |
"5/16", | |
"3/8", | |
"7/16", | |
"1/2", | |
"9/16", | |
"5/8", | |
"11/16", | |
"3/4", | |
"13/16", | |
"7/8", | |
"15/16" | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment