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
function ABS ( x ) { return Math . max ( x , - x ) ; } function findFraction ( x , y , n ) { let A = - 1 , B = - 1 ; for ( let i = 1 ; i <= n ; i ++ ) { let d = Math . floor ( ( i * x ) / y ) ; if ( d >= 0 && ( A == - 1 || ABS ( B * x - y * A ) * ABS ( i * y ) > ABS ( i * x - y * d ) * ABS ( B * y ) ) ) A = d ; B = i ; d ++ ; if ( d >= 0 && ( A == - 1 || ABS ( B * x - y * A ) * ABS ( i * y ) > ABS ( i * x - y * d ) * ABS ( B * y ) ) ) A = d ; B = i ; } A -- ; B -- ; document . write ( A + " " + B ) ; } let x = 3 ; let y = 7 ; let n = 6 ; findFraction ( x , y , n ) ;