VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-number-closest-n-divisible-m/

⇱ Closest to n and Divisible by m - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Closest to n and Divisible by m

Last Updated : 23 Mar, 2026

Given two integers n and m (m != 0). Find the number closest to n and divisible by m. If there is more than one such number, then output the one having maximum absolute value.

Examples:

Input: n = 13, m = 4
Output: 12
Explanation: 12 is the closest to 13, divisible by 4.

Input: n = -15, m = 6
Output: -18
Explanation: Both -12 and -18 are closest to -15, but -18 has the maximum absolute value.

[Naive Approach] Iterative Checking - O(m) Time and O(1) Space

The basic idea is to start checking from n - m to n + m one by one and take the closest number.


Output
12

[Expected Approach] By finding Quotient - O(1) Time and O(1) Space

We first compute the quotient q = n / m, then calculate two candidates:

  • n1 = m * q
    This is the closest multiple of m that is less than or equal to n.
  • n2 = m * (q + 1)orm * (q - 1)
    We choose q + 1 or q - 1 based on the signs of n and m:
    • If n and m have the same sign, use n2 = m * (q + 1)
      This moves in the direction toward n, getting the next closest multiple above n.
    • If n and m have opposite signs, use n2 = m * (q - 1)
      This accounts for the fact that increasing q would move away from n due to the sign flip, so we instead go backward to get the next closest multiple.

Then we return the one (n1 or n2) that has the smaller absolute difference from n.

  • If both have the same distance from n, return the one with the greater absolute value, as required.

Output
12
Comment
Article Tags: