Related Articles
Midy’s theorem
• Difficulty Level : Expert
• Last Updated : 27 Jan, 2021

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.

Examples :

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.

Approach :
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 :

1. Multiply the remainder by 10.
2. Append remainder / denominator to result.
3. 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 :

## C++

 `// C++ implementation as a``// proof of the Midy's theorem``#include ``using` `namespace` `std;` `// Returns repeating sequence of a fraction.``// If repeating sequence doesn't exits,``// then returns -1``string fractionToDecimal(``int` `numerator, ``int` `denominator)``{``    ``string res;` `    ``/* Create a map to store already seen remainders``       ``remainder is used as key and its position in``       ``result is stored as value. Note that we need``       ``position for cases like 1/6. In this case,``       ``the recurring sequence doesn't start from first``       ``remainder. */``    ``map<``int``, ``int``> mp;``    ``mp.clear();``    ` `    ``// Find first remainder``    ``int` `rem = numerator % denominator;` `    ``// Keep finding remainder until either remainder``    ``// becomes 0 or repeats``    ``while` `((rem != 0) && (mp.find(rem) == mp.end()))``    ``{``        ``// Store this remainder``        ``mp[rem] = res.length();` `        ``// Multiply remainder with 10``        ``rem = rem * 10;` `        ``// Append rem / denr to result``        ``int` `res_part = rem / denominator;``        ``res += to_string(res_part);` `        ``// Update remainder``        ``rem = rem % denominator;``    ``}``    ``return` `(rem == 0) ? ``"-1"` `: res.substr(mp[rem]);``}` `// Checks whether a number is prime or not``bool` `isPrime(``int` `n)``{``    ``for` `(``int` `i = 2; i <= n / 2; i++)    ``        ``if` `(n % i == 0)``            ``return` `false``;``   ``return` `true``;``}` `// If all conditions are met,``// it proves Midy's theorem``void` `Midys(string str, ``int` `n)``{``    ``int` `l = str.length();``    ``int` `part1 = 0, part2 = 0;``    ``if` `(!isPrime(n))   ``    ``{``        ``cout << ``"Denominator is not prime, "``             ``<< ``"thus Midy's theorem is not applicable"``;``    ``}``    ``else` `if` `(l % 2 == 0)``    ``{``        ``for` `(``int` `i = 0; i < l / 2; i++)``        ``{``            ``part1 = part1 * 10 + (str[i] - ``'0'``);``            ``part2 = part2 * 10 + (str[l / 2 + i] - ``'0'``);``        ``}``        ``cout << part1 << ``" + "` `<< part2 << ``" = "``             ``<< (part1 + part2) << endl;``        ``cout << ``"Midy's theorem holds!"``;``    ``}``    ``else``    ``{``        ``cout << ``"The repeating decimal is of odd length "``             ``<< ``"thus Midy's theorem is not applicable"``;``    ``}``}` `// Driver code``int` `main()``{``    ``int` `numr = 2, denr = 11;``    ``string res = fractionToDecimal(numr, denr);``    ``if` `(res == ``"-1"``)``        ``cout << ``"The fraction does not have repeating decimal"``;``    ``else` `{``        ``cout << ``"Repeating decimal = "` `<< res << endl;``        ``Midys(res, denr);``    ``}``    ``return` `0;``}`

## Java

 `// Java implementation as a``// proof of the Midy's theorem``import` `java.util.*;` `class` `GFG{` `// Returns repeating sequence of a fraction.``// If repeating sequence doesn't exits,``// then returns -1``static` `String fractionToDecimal(``int` `numerator,``                                ``int` `denominator)``{``    ``String res = ``""``;` `    ``/* Create a map to store already seen remainders``    ``remainder is used as key and its position in``    ``result is stored as value. Note that we need``    ``position for cases like 1/6. In this case,``    ``the recurring sequence doesn't start from first``    ``remainder. */``    ``HashMap mp = ``new` `HashMap<>();``    ` `    ``// Find first remainder``    ``int` `rem = numerator % denominator;` `    ``// Keep finding remainder until either remainder``    ``// becomes 0 or repeats``    ``while` `((rem != ``0``) && !mp.containsKey(rem))``    ``{``        ` `        ``// Store this remainder``        ``mp.put(rem, res.length());` `        ``// Multiply remainder with 10``        ``rem = rem * ``10``;` `        ``// Append rem / denr to result``        ``int` `res_part = rem / denominator;``        ``res += res_part + ``""``;` `        ``// Update remainder``        ``rem = rem % denominator;``    ``}``    ` `    ``return` `(rem == ``0``) ? ``"-1"` `: res.substring(mp.get(rem));``}` `// Checks whether a number is prime or not``static` `boolean` `isPrime(``int` `n)``{``    ``for``(``int` `i = ``2``; i <= n / ``2``; i++)``        ``if` `(n % i == ``0``)``            ``return` `false``;``            ` `    ``return` `true``;``}` `// If all conditions are met,``// it proves Midy's theorem``static` `void` `Midys(String str, ``int` `n)``{``    ``int` `l = str.length();``    ``int` `part1 = ``0``, part2 = ``0``;``    ` `    ``if` `(!isPrime(n))   ``    ``{``        ``System.out.print(``"Denominator is not prime, "` `+``                         ``"thus Midy's theorem is not "` `+``                         ``"applicable"``);``    ``}``    ``else` `if` `(l % ``2` `== ``0``)``    ``{``        ``for``(``int` `i = ``0``; i < l / ``2``; i++)``        ``{``            ``part1 = part1 * ``10` `+ (str.charAt(i) - ``'0'``);``            ``part2 = part2 * ``10` `+ (str.charAt(l / ``2` `+ i) - ``'0'``);``        ``}``        ``System.out.println(part1 + ``" + "` `+ part2 +``                           ``" = "` `+ (part1 + part2));``        ``System.out.print(``"Midy's theorem holds!"``);``    ``}``    ``else``    ``{``        ``System.out.print(``"The repeating decimal is "` `+``                         ``"of odd length thus Midy's "``+``                         ``"theorem is not applicable"``);``    ``}``}` `// Driver code``public` `static` `void` `main(String []args)``{``    ``int` `numr = ``2``, denr = ``11``;``    ``String res = fractionToDecimal(numr, denr);``    ` `    ``if` `(res == ``"-1"``)``        ``System.out.print(``"The fraction does not "` `+``                         ``"have repeating decimal"``);``    ``else``    ``{``        ``System.out.println(``"Repeating decimal = "` `+ res);``        ``Midys(res, denr);``    ``}``}``}` `// This code is contributed by rutvik_56`

## C#

 `// C# implementation as a``// proof of the Midy's theorem``using` `System;``using` `System.Collections;``using` `System.Collections.Generic;` `class` `GFG{` `// Returns repeating sequence of a fraction.``// If repeating sequence doesn't exits,``// then returns -1``static` `String fractionToDecimal(``int` `numerator,``                                ``int` `denominator)``{``    ``String res = ``""``;` `    ``/* Create a map to store already seen remainders``    ``remainder is used as key and its position in``    ``result is stored as value. Note that we need``    ``position for cases like 1/6. In this case,``    ``the recurring sequence doesn't start from first``    ``remainder. */``    ``Dictionary<``int``,``int``> mp = ``new` `Dictionary<``int``,``int``>();``    ` `    ``// Find first remainder``    ``int` `rem = numerator % denominator;` `    ``// Keep finding remainder until either remainder``    ``// becomes 0 or repeats``    ``while` `((rem != 0) && !mp.ContainsKey(rem))``    ``{``        ` `        ``// Store this remainder``        ``mp[rem]= res.Length;` `        ``// Multiply remainder with 10``        ``rem = rem * 10;` `        ``// Append rem / denr to result``        ``int` `res_part = rem / denominator;``        ``res += res_part + ``""``;` `        ``// Update remainder``        ``rem = rem % denominator;``    ``}``    ` `    ``return` `(rem == 0) ? ``"-1"` `: res.Substring(mp[rem]);``}` `// Checks whether a number is prime or not``static` `bool` `isPrime(``int` `n)``{``    ``for``(``int` `i = 2; i <= n / 2; i++)``        ``if` `(n % i == 0)``            ``return` `false``;          ``    ``return` `true``;``}` `// If all conditions are met,``// it proves Midy's theorem``static` `void` `Midys(String str, ``int` `n)``{``    ``int` `l = str.Length;``    ``int` `part1 = 0, part2 = 0;  ``    ``if` `(!isPrime(n))   ``    ``{``        ``Console.Write(``"Denominator is not prime, "` `+``                         ``"thus Midy's theorem is not "` `+``                         ``"applicable"``);``    ``}``    ``else` `if` `(l % 2 == 0)``    ``{``        ``for``(``int` `i = 0; i < l / 2; i++)``        ``{``            ``part1 = part1 * 10 + (str[i] - ``'0'``);``            ``part2 = part2 * 10 + (str[l / 2 + i] - ``'0'``);``        ``}``        ``Console.WriteLine(part1 + ``" + "` `+ part2 +``                           ``" = "` `+ (part1 + part2));``        ``Console.Write(``"Midy's theorem holds!"``);``    ``}``    ``else``    ``{``        ``Console.Write(``"The repeating decimal is "` `+``                         ``"of odd length thus Midy's "``+``                         ``"theorem is not applicable"``);``    ``}``}` `// Driver code``public` `static` `void` `Main(``string` `[]args)``{``    ``int` `numr = 2, denr = 11;``    ``string` `res = fractionToDecimal(numr, denr);``    ` `    ``if` `(res == ``"-1"``)``        ``Console.Write(``"The fraction does not "` `+``                         ``"have repeating decimal"``);``    ``else``    ``{``        ``Console.WriteLine(``"Repeating decimal = "` `+ res);``        ``Midys(res, denr);``    ``}``}``}` `// This code is contributed by pratham76.`

Output :

```Repeating decimal = 18
1 + 8 = 9
Midy's theorem holds!```

More about Midy’s theorem can be found on
http://www.kurims.kyoto-u.ac.jp/EMIS/journals/INTEGERS/papers/h2/h2.pdf
http://digitalcommons.unl.edu/cgi/viewcontent.cgi?article=1047&context=mathfacpub

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up