格式化选择器上的分数到最小公分母?

时间:2012-04-24 03:12:31

标签: iphone ios arrays format picker

以下是我目前如何格式化我的选择器。我真的希望它显示1/8而不是2/16或1/2而不是8/16。如何调整此项以显示我想要的输出?谢谢!

fractionArray = [[NSMutableArray alloc] init];
for(int frac = 0; frac <= 15; frac ++){ 
    NSString *fracString = [NSString stringWithFormat:@"%d/16", frac];
    [fractionArray addObject:fracString]; // Add the string.

2 个答案:

答案 0 :(得分:2)

这适用于任何2分母的力量:

// 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.
}

很容易将其扩展到任何分母。 (提示:将n替换为n,将n从2扩展到sqrt(分母)。)

编辑:实际上现在有效!


因为我继续编码,所以这是影响任何分母的版本:

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];
}

答案 1 :(得分:2)

这些天的孩子...... Euclidean algorithm ......他们在学校教什么......发牢骚地抱怨......

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];
}