Find the closest Fraction to given fraction having minimum absolute difference | C ++ program for the above approach ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long ABS ( long long x ) { return max ( x , - x ) ; } void findFraction ( long long x , long long y , long long n ) { long long A = -1 , B = -1 ; for ( long long i = 1 ; i <= n ; i ++ ) { long long d = ( 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 ; } cout << A << " / " << B << endl ; } int main ( ) { long long x = 3 , y = 7 , n = 6 ; findFraction ( x , y , n ) ; return 0 ; }