Midy 's theorem | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; string fractionToDecimal ( int numerator , int denominator ) { string res ; map < int , int > mp ; mp . clear ( ) ; int rem = numerator % denominator ; while ( ( rem != 0 ) && ( mp . find ( rem ) == mp . end ( ) ) ) { mp [ rem ] = res . length ( ) ; rem = rem * 10 ; int res_part = rem / denominator ; res += to_string ( res_part ) ; rem = rem % denominator ; } return ( rem == 0 ) ? " - 1" : res . substr ( mp [ rem ] ) ; } bool isPrime ( int n ) { for ( int i = 2 ; i <= n / 2 ; i ++ ) if ( n % i == 0 ) return false ; return true ; } 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 " ; } } 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 ; }