text: Smallest divisor of N closest to X | 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 ; Given N & X ; Function Call
code: function findClosest ( N , target ) { let closest = - 1 ; let diff = Number . MAX_VALUE ; for ( let 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 ; } } } } document . write ( closest ) ; } let N = 16 , X = 5 ; findClosest ( N , X ) ;