text: Smallest divisor of N closest to X | C ++ program for the above approach ; Function to find the divisor of N closest to the target ; Iterate till square root of N ; Check if divisors are equal ; Check if i is the closest ; Check if i is the closest ; Check if n / i is the closest ; Print the closest value ; Driver Code ; Given N & X ; Function Call
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; int findClosest ( int N , int target ) { int closest = -1 ; int diff = INT_MAX ; for ( int i = 1 ; i <= sqrt ( N ) ; i ++ ) { if ( N % i == 0 ) { if ( N / i == i ) { if ( abs ( target - i ) < diff ) { diff = abs ( target - i ) ; closest = i ; } } else { if ( abs ( target - i ) < diff ) { diff = abs ( target - i ) ; closest = i ; } if ( abs ( target - N / i ) < diff ) { diff = abs ( target - N / i ) ; closest = N / i ; } } } } cout << closest ; } int main ( ) { int N = 16 , X = 5 ; findClosest ( N , X ) ; return 0 ; }