Midy 's theorem | Java implementation as a proof of the Midy 's theorem ; Returns repeating sequence of a fraction . If repeating sequence doesn 't exits, then returns -1 ; 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.  ; Find first remainder ; Keep finding remainder until either remainder becomes 0 or repeats ; Store this remainder ; Multiply remainder with 10 ; Append rem / denr to result ; Update remainder ; Checks whether a number is prime or not ; If all conditions are met , it proves Midy 's theorem ; Driver code
import java . util . * ; class GFG { static String fractionToDecimal ( int numerator , int denominator ) { String res = " " ; HashMap < Integer , Integer > mp = new HashMap < > ( ) ; int rem = numerator % denominator ; while ( ( rem != 0 ) && ! mp . containsKey ( rem ) ) { mp . put ( rem , res . length ( ) ) ; rem = rem * 10 ; int res_part = rem / denominator ; res += res_part + " " ; rem = rem % denominator ; } return ( rem == 0 ) ? " - 1" : res . substring ( mp . get ( rem ) ) ; } static boolean isPrime ( int n ) { for ( int i = 2 ; i <= n / 2 ; i ++ ) if ( n % i == 0 ) return false ; return true ; } 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 " ) ; } } 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 ) ; } } }