How to simplify fractions in C#?

前端 未结 5 2364
暗喜
暗喜 2020-12-11 17:55

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 r

5条回答
  •  既然无缘
    2020-12-11 18:39

    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).

提交回复
热议问题