How to know the repeating decimal in a fraction?

后端 未结 5 1623
庸人自扰
庸人自扰 2020-11-29 09:42

I already know when a fraction is repeating decimals. Here is the function.

public bool IsRepeatingDecimal
{
    get
    {
        if (Numerator % Denominato         


        
5条回答
  •  悲哀的现实
    2020-11-29 09:51

    The long division algorithm is pretty good, so I have nothing to add there.

    But note that your algorithm IsRepeatingDecimal may not work and is inneficient.

    It will not work if your fraction is not irreductible, that is if there exists an integer larger than 1 that divides both your numerator and your denominator. For example, if you feed 7/14 then your algorithm will return true when it should return false.

    To reduce your fraction, find the gcd between both numerator and denominator and divide both by this gcd.

    If you assume that the fraction is irreducible, then your test

    if (Numerator % Denominator == 0)
    

    can simply be replaced with

    if (Denominator == 1)
    

    But that is still unnecessary since if Denominator is 1, then your list 'primes' is going to be empty and your algorithm will return false anyway.

    Finally, calling MathAlgorithms.Primes(Denominator) is going to be expensive for large numbers and can be avoided. Indeed, all you need to do is divide your denominator by 5 (respectively 2) untill it is no longer divisible by 5 (resp. 2). If the end result is 1, then return false, otherwise return true.

提交回复
热议问题