Find the number closest to n and divisible by m | function to find the number closest to n and divisible by m ; find the quotient ; 1 st possible closest number ; 2 nd possible closest number ; if true , then n1 is the required closest number ; else n2 is the required closest number ; Driver Code
function closestNumber ( n , m ) { let q = parseInt ( n / m ) ; let n1 = m * q ; let n2 = ( n * m ) > 0 ? ( m * ( q + 1 ) ) : ( m * ( q - 1 ) ) ; if ( Math . abs ( n - n1 ) < Math . abs ( n - n2 ) ) return n1 ; return n2 ; } let n = 13 ; let m = 4 ; document . write ( closestNumber ( n , m ) + " " ) ; n = - 15 ; m = 6 ; document . write ( closestNumber ( n , m ) + " " ) ; n = 0 ; m = 8 ; document . write ( closestNumber ( n , m ) + " " ) ; n = 18 ; m = - 7 ; document . write ( closestNumber ( n , m ) + " " ) ;