-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathNearNo.java
More file actions
27 lines (25 loc) · 847 Bytes
/
NearNo.java
File metadata and controls
27 lines (25 loc) · 847 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package accentureQ;
import java.util.Scanner;
public class NearNo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Num");
int num = sc.nextInt();
System.out.println("m");
int m = sc.nextInt();
int diff = Integer.MAX_VALUE;
int x = 0;
int closestNum = 0;
for (int i = 1; i < num / 2; i++) {
x = m * i;
int currDiff = Math.abs(num - x);
if (currDiff <= diff) {
diff = currDiff;
closestNum = x;
} else {
break; // As the difference starts increasing beyond this point, no need to continue.
}
}
System.out.println("Closest number divisible by m: " + closestNum);
}
}