Find the closest Fraction to given fraction having minimum absolute difference | Function to find the absolute value of x ; Function to find the fraction with minimum absolute difference ; Initialize the answer variables ; Iterate over the range ; Nearest fraction ; x / y - d / i < x / y - A / B ( B * x - y * A ) * ( i * y ) > ( i * x - y * d ) * ( B * y ) ; Check for d + 1 ; Print the answer ; Driver Code
def ABS ( x ) : NEW_LINE INDENT return max ( x , - x ) NEW_LINE DEDENT def findFraction ( x , y , n ) : NEW_LINE INDENT A = - 1 NEW_LINE B = - 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT d = ( i * x ) // y NEW_LINE if ( d >= 0 and ( A == - 1 or ABS ( B * x - y * A ) * ABS ( i * y ) > ABS ( i * x - y * d ) * ABS ( B * y ) ) ) : NEW_LINE INDENT A = d NEW_LINE B = i NEW_LINE DEDENT d += 1 NEW_LINE if ( d >= 0 and ( A == - 1 or ABS ( B * x - y * A ) * ABS ( i * y ) > ABS ( i * x - y * d ) * ABS ( B * y ) ) ) : NEW_LINE INDENT A = d NEW_LINE B = i NEW_LINE DEDENT DEDENT print ( str ( A ) + " / " + str ( B ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT x = 3 NEW_LINE y = 7 NEW_LINE n = 6 NEW_LINE findFraction ( x , y , n ) NEW_LINE DEDENT