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 program to test above
def closestNumber ( n , m ) : NEW_LINE INDENT q = int ( n / m ) NEW_LINE n1 = m * q NEW_LINE if ( ( n * m ) > 0 ) : NEW_LINE INDENT n2 = ( m * ( q + 1 ) ) NEW_LINE DEDENT else : NEW_LINE INDENT n2 = ( m * ( q - 1 ) ) NEW_LINE DEDENT if ( abs ( n - n1 ) < abs ( n - n2 ) ) : NEW_LINE INDENT return n1 NEW_LINE DEDENT return n2 NEW_LINE DEDENT n = 13 ; m = 4 NEW_LINE print ( closestNumber ( n , m ) ) NEW_LINE n = - 15 ; m = 6 NEW_LINE print ( closestNumber ( n , m ) ) NEW_LINE n = 0 ; m = 8 NEW_LINE print ( closestNumber ( n , m ) ) NEW_LINE n = 18 ; m = - 7 NEW_LINE print ( closestNumber ( n , m ) ) NEW_LINE