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: using System ; class GFG { static void findClosest ( int N , int target ) { int closest = - 1 ; int diff = Int32 . MaxValue ; for ( int i = 1 ; i <= Math . Sqrt ( N ) ; i ++ ) { if ( N % i == 0 ) { if ( N / i == i ) { if ( Math . Abs ( target - i ) < diff ) { diff = Math . Abs ( target - i ) ; closest = i ; } } else { if ( Math . Abs ( target - i ) < diff ) { diff = Math . Abs ( target - i ) ; closest = i ; } if ( Math . Abs ( target - N / i ) < diff ) { diff = Math . Abs ( target - N / i ) ; closest = N / i ; } } } } Console . Write ( closest ) ; } static void Main ( ) { int N = 16 , X = 5 ; findClosest ( N , X ) ; } }