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
< ? php function closestNumber ( $ n , $ m ) { $ q = ( int ) ( $ n / $ m ) ; $ n1 = $ m * $ q ; $ n2 = ( $ n * $ m ) > 0 ? ( $ m * ( $ q + 1 ) ) : ( $ m * ( $ q - 1 ) ) ; if ( abs ( $ n - $ n1 ) < abs ( $ n - $ n2 ) ) return $ n1 ; return $ n2 ; } $ n = 13 ; $ m = 4 ; echo closestNumber ( $ n , $ m ) , " STRNEWLINE " ; $ n = -15 ; $ m = 6 ; echo closestNumber ( $ n , $ m ) , " STRNEWLINE " ; $ n = 0 ; $ m = 8 ; echo closestNumber ( $ n , $ m ) , " STRNEWLINE " ; $ n = 18 ; $ m = -7 ; echo closestNumber ( $ n , $ m ) , " STRNEWLINE " ; ? >