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.
- Find a triplet in an array whose sum is closest to a given number
- Find number from given list for which value of the function is closest to A
- Find the closest and smaller tidy number
- Find if a number is divisible by every number in a list
- Find N digits number which is divisible by D
- Find nth number that contains the digit k or divisible by k.
- Find Nth smallest number that is divisible by 100 exactly K times
- Find the first natural number whose factorial is divisible by x
- Find the maximum number of elements divisible by 3
- Find the multiple of x which is closest to a^b
- Find the Sub-array with sum closest to 0
- 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 K Closest Points to the Origin
- Find multiple of x closest to or a ^ b (a raised to power b)
- Find permutation of n which is divisible by 3 but not divisible by 6