Algorithm for detecting repeating decimals?

前端 未结 6 2033
悲&欢浪女
悲&欢浪女 2020-12-10 05:23

Is there an algorithm for figuring out the following things?

  1. If the result of a division is a repeating decimal (in binary).
  2. If it repeats, at what di
6条回答
  •  不知归路
    2020-12-10 05:59

    I can give a hint - repeating decimals in base ten are all fraction with the denominator having at least one prime factors other than two and five. If the denominator contains no prime factors two or five, they can always be represented with a denominator of all nines. Then the nominator is the repeating part and the number of nines is the length of the repeating part.

    3     _
    - = 0.3
    9
    
    1   142857     ______
    - = ------ = 0.142857
    7   999999
    

    If there are prime factors two or five in the denominator, the repeating part starts not at the first position.

    17    17        ______
    -- = ----- = 0.4857142
    35   5 * 7
    

    But I cannot remember how to derive the non-repeating part and its length.

    This seem to translate well to base two. Only fraction with a power of two denominator are non-repeating. This can be easily checked by asserting that only a single bit in the denominator is set.

    1/2 =   1/10   = 0.1
    1/4 =   1/100  = 0.01
    3/4 =  11/100  = 0.11
    5/8 = 101/1000 = 0.101
    

    All fraction with odd denominators should be repeating and the pattern and its length can be obtained by expressing the fraction with a denominator in the form 2^n-1.

                                                         __
     1/3            =  1/(2^2-1) =        1/11       = 0.01
                                                         __
     2/3            =  2/(2^2-1) =       10/11       = 0.10
                           __
     4/3  => 1 + 1/3 =>  1.01
                           __
    10/3  => 3 + 1/3 => 11.01
                                                         ____
     1/5  =   3/15  =  3/(2^4-1) =       11/1111     = 0.0011
                                                         ________
    11/17 = 165/255 = 11/(2^8-1) = 10100101/11111111 = 0.10100101
    

    As for base ten, I cannot tell how to handle denominators containing but not being a power of two - for example 12 = 3 * 2^2.

提交回复
热议问题