Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

math - How to simplify fractions in C#?

I'm looking for a library or existing code to simplify fractions.

Does anyone have anything at hand or any links?

P.S. I already understand the process but really don't want to rewrite the wheel

Update

Ok i've checked out the fraction library on the CodeProject BUT the problem I have is a little bit tricker than simplifying a fraction.

I have to reduce a percentage split which could be 20% / 50% / 30% (always equal to 100%)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think you just need to divide by the GCD of all the numbers.

void Simplify(int[] numbers)
{
    int gcd = GCD(numbers);
    for (int i = 0; i < numbers.Length; i++)
        numbers[i] /= gcd;
}
int GCD(int a, int b)
{
    while (b > 0)
    {
        int rem = a % b;
        a = b;
        b = rem;
    }
    return a;
}
int GCD(int[] args)
{
    // using LINQ:
    return args.Aggregate((gcd, arg) => GCD(gcd, arg));
}

I haven't tried the code, but it seems simple enough to be right (assuming your numbers are all positive integers and you don't pass an empty array).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...