This should work for any power of 2 denominator:
// dodge this special case:
[fractionArray addObject:@"0"];
for ( int numerator = 1; numerator <= 15; numerator++ )
{
int denominator = 16;
int num = numerator;
while ( num % 2 == 0 )
{
num /= 2;
denominator /= 2;
}
NSString *fracString = [NSString stringWithFormat:@"%d/%d", num, denominator];
[fractionArray addObject:fracString]; // Add the string.
}
And it's easy to extend this to any denominator. (Hint: replace 2 with n, iterate n from 2 up to sqrt(denominator).)
EDIT: actually works now!
Since I went ahead and coded it, here's the version that factors any denominator:
int denominator = 240;
for ( int numerator = 1; numerator < denominator; numerator++ )
{
int denom = denominator;
int num = numerator;
int factor = 2;
while ( factor * factor < denom )
{
while ( (num % factor) == 0 && (denom % factor) == 0 )
{
num /= factor;
denom /= factor;
}
// don't worry about finding the next prime,
// the loop above will skip composites
++factor;
}
NSString *fracString = [NSString stringWithFormat:@"%d/%d", num, denom];
[fractionArray addObject:fracString];
}