Algorithm for detecting repeating decimals?

前端 未结 6 1973
悲&欢浪女
悲&欢浪女 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:39

    You can do a long division, noting the remainders. The structure of the remainders will give you the structure of any rational decimal:

    1. the last remainder is zero: it is a decimal without any repeating part
    2. the first and the last remainder are equal: the decimal is repeating right after the dot
    3. the distance between the first and the first remainder equal to the last are the non-repeating digits, the remainder is the repeating part

    In general the distances will give you the amount of digits for each part.

    You can see this algorithm coded in C++ in the method decompose() here.

    Try 228142/62265, it has a period of 1776 digits!

提交回复
热议问题