Algorithm for detecting repeating decimals?

前端 未结 6 1995
悲&欢浪女
悲&欢浪女 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条回答
  •  萌比男神i
    2020-12-10 05:44

    First of all, one of your examples is wrong. The repeating part of 1/5 is 0011 rather than 1100, and it begins at the very beginning of the fractional part.

    A repeating decimal is something like:

    a/b = c + d(2-n + 2-n-k + 2-n-2k + ...)
        = c + 2-n * d / (1 - 2-k)

    in which n and d are what you want.

    For example,

    1/10(dec) = 1/1010(bin) = 0.0001100110011... // 1 = true, 2 = -1, 3 = 0011

    could be represented by the formula with

    a = 1, b = 10(dec), c = 0, d = 0.0011(bin), n = 1, k = 4;
    (1 - 2-k) = 0.1111

    Therefore, 1/10 = 0.1 * 0.0011/0.1111. The key part of a repeating decimal representation is generated by dividing by (2n - 1) or its any multiple of 2. So you can either find a way to express your denominator as such (like building constant tables), or do a big number division (which is relatively slow) and find the loop. There's no quick way to do this.

提交回复
热议问题