text: Smallest divisor of N closest to X | Define macros ; Stores divisors for all numbers in the vector divisors ; i is the divisor and j is the multiple ; Function to compare the closeness of the given target ; Function to find the element closest to target in divisors vector ; Corner cases ; Perform binary search ; Check if target is less than the array element then search in left half ; Check if target is greater than previous to mid , return closest of two ; Repeat for left half ; Check if target is greater than mid ; Update i ; Only single element left after search ; Function to print the divisor of N closest to X ; Function call to calculate and stores divisors of all numbers in a vector ; Stores the closest value to target ; Print the answer ; Given N & X ; Function Call
code: let MAX = 10000 ; let divisors = new Array ( MAX + 1 ) ; function computeDivisors ( ) { for ( let i = 1 ; i <= MAX ; i ++ ) { for ( let j = i ; j <= MAX ; j += i ) { divisors [ j ] . push ( i ) ; } } } function getClosest ( val1 , val2 , target ) { if ( target - val1 >= val2 - target ) return val2 ; else return val1 ; } function findClosest ( arr , n , target ) { if ( target <= arr [ 0 ] ) return arr [ 0 ] ; if ( target >= arr [ n - 1 ] ) return arr [ n - 1 ] ; let i = 0 , j = n , mid = 0 ; while ( i < j ) { mid = Math . floor ( ( i + j ) / 2 ) ; if ( arr [ mid ] == target ) return arr [ mid ] ; if ( target < arr [ mid ] ) { if ( mid > 0 && target > arr [ mid - 1 ] ) return getClosest ( arr [ mid - 1 ] , arr [ mid ] , target ) ; j = mid ; } else { if ( mid < n - 1 && target < arr [ mid + 1 ] ) return getClosest ( arr [ mid ] , arr [ mid + 1 ] , target ) ; i = mid + 1 ; } } return arr [ mid ] ; } function printClosest ( N , X ) { computeDivisors ( ) ; let ans = findClosest ( divisors [ N ] , divisors [ N ] . length , X ) ; document . write ( ans ) ; } let N = 16 , X = 5 ; for ( let i = 0 ; i < divisors . length ; i ++ ) divisors [ i ] = [ ] ; printClosest ( N , X ) ;