Problem: Closest Number

You are given 3 numbers ab and x. You need to output the multiple of x which is closest to ab. If more than one answer exists , display the smallest one.

Input Format
The first line contains T, the number of testcases.
T lines follow, each line contains 3 space separated integers (ab and x respectively)

Output Format
For each test case , output the multiple of x which is closest to ab

Constraints
1 ≤ T ≤ 105
1 ≤ x ≤ 109
0 < ab ≤ 109
1 ≤ a ≤ 109
-109 ≤ b ≤ 109

Sample Input

3
349 1 4
395 1 7
4 -2 2

Sample Output

348
392
0

Explanation

The closest multiple of 4 to 349 is 348.
The closest multiple of 7 to 395 is 392.
The closest multiple of 2 to 1/16 is 0.

Hint:
First case: b is negative, so (int)pow(a,b) will be always less than 1, so the multiple of x to pow(a,b) would be zero
Second case: b is positive. First, calculate pow(a,b), then calculate the result of redundant devision of pow(a,b) and x. (pow(a,b) % x)
-If (abs((redundant – x + pow(a,b)) – pow(a,b) <= abs((pow(a,b) – redundant)) – pow(a,b))
multiple of x to pow(a,b) would be : pow(a,b) + (x – redundant); //because x is always bigger than redundant
else : multiple of x to pow(a,b) would be : pow(a,b) – redundant;

Java code:

import java.util.Scanner;

public class Solution {
public static void main(String[] args){
int T;
long a,b,x;
long[] array;
Scanner input = new Scanner(System.in);
T = input.nextInt();
array = new long[T];
for(int count = 0; count &lt; T; ++count){
a = input.nextLong();
b = input.nextLong();
x = input.nextLong();
long pow = (long)Math.pow(a, b);
if(pow == 0)
array[count] = 0;
else{
if(Math.abs((pow - (pow % x))-pow) &lt;= Math.abs( (pow + x -(pow % x)) - pow))
array[count] = pow - (pow % x);
else
array[count] = pow + (x - (pow % x));
}
}
for(int count = 0; count &lt; T; ++count)
System.out.println(array[count]);
}
}
Advertisements