Closest Number

Easy
0/40
Average time to solve is 15m
1 upvote
Asked in companies
MicrosoftArcesiumExpedia Group

Problem statement

You are given two integers N and M. Can you find a number closest to N and divisible by M.

Here closest number to N means a number whose absolute difference is minimum with N. If there are two integers closest to N then the answer will be the one which is a smaller integer.

For Example:

Let N = 8 and M = 3
The numbers divisible by 3 are 3, 6, 9, …
From these numbers 9 is closest to 8. Thus, the answer is 9.
Detailed explanation ( Input/output format, Notes, Images )
Input format:
The first line of input contains an integer ‘T’ denoting the number of test cases.

The first and only line of each test case contains two integers N and M.
Output format :
For each test case, return an integer closest to N and divisible by M.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 10^5
-10^9 <= N <= 10^9
1 <= M <= 10^9

Time limit: 1 sec
Sample Input 1:
2
8 3
-15 6
Sample Output 1:
9
-18
Explanation
Test Case 1:
Refer to the example described above.

Test Case 2:
The closest number to -15 which is divisible by 6 are -12 and -18 as the absolute difference of both by -15 is equal to 3. So, the answer will be -18 as it is smaller than -12.
Sample Input 2:
3
13 4
14 4
15 4
Sample Output 2:
12
12
16
Hint

The brute force approach is to loop over the number closest to N and find the one which is divisible by M.

Approaches (2)
Brute Force

The brute force approach is to loop over the number closest to N and find the one which is divisible by M.

  • Run a loop from 0 to M-1:
    • Check if N - i is divisible by M, if yes return N - i
    • Check if N + i is divisible by M, if yes return N + i
Time Complexity

O(M) per test case where M is the dividing number.

 

In the worst case, we will be running a loop M times.

Space Complexity

O(1) per test case.

 

In the worst case, we are using constant extra space.

Code Solution
(100% EXP penalty)
Closest Number
Full screen
Console