FIND CLOSEST NUMBER
Given non-zero two integers N and M. The problem is to find the number closest to Nand divisible by M. If there are more than one such number, then output the one havingmaximum absolute value.
Input:
The first line consists of an integer T i.e number of test cases. T testcases follow. The first and only line of each test case contains two space separated integers N and M.
The first line consists of an integer T i.e number of test cases. T testcases follow. The first and only line of each test case contains two space separated integers N and M.
Output:
For each testcase, in a new line, print the closest number to N which is also divisible by M.
For each testcase, in a new line, print the closest number to N which is also divisible by M.
Constraints:
1 <= T <= 100
-1000 <= N, M <= 1000
1 <= T <= 100
-1000 <= N, M <= 1000
Example:
Input:
2
13 4
-15 6
Output:
12
-18
Input:
2
13 4
-15 6
Output:
12
-18
import java.util.Scanner;
import java.lang.Math;
class Closest
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
int t=s.nextInt();
double c,d;
for(int i=0;i<t;i++)
{
double a=s.nextInt();
double b=s.nextInt();
d=Math.abs(a);
c=d%b;
if(a>0){
if(c<(b/2))
{
System.out.println((int)(d-c));
}
else{
System.out.println((int)(d+b-c));
}
}
else
{
if(c<(b/2))
{
System.out.println(-(int)(d-c));
}
else{
System.out.println(-(int)(d+b-c));
}
}
}
}
}
Comments
Post a Comment