According to Midy’s theorem, if the period of a repeating decimal for , where p is prime and is a reduced fraction, has an even number of digits, then dividing the repeating portion into halves and adding gives a string of 9s.
a = 1 and p = 7
1/7 = 0.14285714285..
So 1/7 is a repeating decimal with 142857 being repeated. Now, according to the theorem, it has even number of repeating digits i.e. 142857. Further if we divide this into two halves, we get 142 and 857. Thus, on adding these two, we get 999 which is string of 9s and matches our theorem.
a = 2 and p = 11
2/11 = 0.18181818181..
Here, repeating decimal is 18. Now this is even in number therefore 1+8 = 9 which again shows the validity of Midy’s theorem.
Given numerator and denominator, the task is to find if the resultant floating point number follows Midy’s theorem or not.
Let us simulate the process of converting fraction to decimal. Let us look at the part where we have already figured out the integer part which is floor(numerator/denominator). Now we are left with ( remainder = numerator%denominator ) / denominator.
If you remember the process of converting to decimal, at each step we do the following :
- Multiply the remainder by 10.
- Append remainder / denominator to result.
- Remainder = remainder % denominator.
At any moment, if remainder becomes 0, we are done.
However, when there is a recurring sequence, remainder never becomes 0. For example if you look at 1/3, the remainder never becomes 0.
Below is one important observation :
If we start with remainder ‘rem’ and if the remainder repeats at any point of time, the digits between the two occurrence of ‘rem’ keep repeating.
So the idea is to store seen remainders in a map. Whenever a remainder repeats, we return the sequence before the next occurrence.
Below is the implementation of Midy’s theorem :
Repeating decimal = 18 1 + 8 = 9 Midy's theorem holds!
More about Midy’s theorem can be found on