Expressing a fraction as a natural number under modulo ' m ' | Python3 implementation of the approach ; Function to return the GCD of given numbers ; Recursive function to return ( x ^ n ) % m ; Function to return the fraction modulo mod ; ( b ^ m - 2 ) % m ; Final answer ; Driver code
m = 1000000007 NEW_LINE def gcd ( a , b ) : NEW_LINE INDENT if ( a == 0 ) : NEW_LINE INDENT return b NEW_LINE DEDENT return gcd ( b % a , a ) NEW_LINE DEDENT def modexp ( x , n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT elif ( n % 2 == 0 ) : NEW_LINE INDENT return modexp ( ( x * x ) % m , n // 2 ) NEW_LINE DEDENT else : NEW_LINE INDENT return ( x * modexp ( ( x * x ) % m , ( n - 1 ) / 2 ) % m ) NEW_LINE DEDENT DEDENT def getFractionModulo ( a , b ) : NEW_LINE INDENT c = gcd ( a , b ) NEW_LINE a = a // c NEW_LINE b = b // c NEW_LINE d = modexp ( b , m - 2 ) NEW_LINE ans = ( ( a % m ) * ( d % m ) ) % m NEW_LINE return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = 2 NEW_LINE b = 6 NEW_LINE print ( getFractionModulo ( a , b ) ) NEW_LINE DEDENT