Given two integers n and m. The problem is to find the number closest to n and divisible by m. If there are more than one such number, then output the one having maximum absolute value. If n is completely divisible by m, then output n only. Time complexity of O(1) is required.
Constraints: m != 0
Input : n = 13, m = 4 Output : 12 Input : n = -15, m = 6 Output : -18 Both -12 and -18 are closest to -15, but -18 has the maximum absolute value.
We find value of n/m. Let this value be q. Then we find closest of two possibilities. One is q * m other is (m * (q + 1)) or (m * (q – 1)) depending on whether one of the given two numbers is negative or not.
closestNumber(n, m) Declare q, n1, n2 q = n / m n1 = m * q if (n * m) > 0 n2 = m * (q + 1) else n2 = m * (q - 1) if abs(n-n1) < abs(n-n2) return n1 return n2
12 -18 0 21
Time Complexity: O(1)
This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Find the closest and smaller tidy number
- Find number from given list for which value of the function is closest to A
- Find the greater number closest to N having at most one non-zero digit
- Find a triplet in an array whose sum is closest to a given number
- Find permutation of n which is divisible by 3 but not divisible by 6
- Minimum absolute difference of a number and its closest prime
- Count the number of pairs (i, j) such that either arr[i] is divisible by arr[j] or arr[j] is divisible by arr[i]
- Find the Sub-array with sum closest to 0
- Find multiple of x closest to or a ^ b (a raised to power b)
- Find the multiple of x which is closest to a^b
- Queries to find the future closest date
- Find closest integer with the same weight
- Find the K closest points to origin using Priority Queue
- Find K Closest Points to the Origin
- Minimum number closest to N made up of odd digits only
- Smaller palindromic number closest to N
- Closest perfect square and its distance
- Bitwise AND of sub-array closest to K
- Two elements whose sum is closest to zero
- Multiple of x closest to n