Example.
int a = 254;
int b = 25;
int c = (closest integer to `a` that is divisible by `b`)
How can I find the integer c
? The result of that example is c = 250
.
There are two cases to consider:
The closest integer that is less than or equal to a
:
int c1 = a - (a % b);
The closest integer that is greater than a
:
int c2 = (a + b) - (a % b);
Then we need to check which is closer to a
and return that:
int c;
if (a - c1 > c2 - a) {
c = c2;
} else {
c = c1;
}
So we could create a closestInteger()
method like this:
static int closestInteger(int a, int b) {
int c1 = a - (a % b);
int c2 = (a + b) - (a % b);
if (a - c1 > c2 - a) {
return c2;
} else {
return c1;
}
}
Example:
System.out.println(closestInteger(254, 25));
System.out.println(closestInteger(9, 5));
Output:
250
10
You have to check on both sides of a
. So we set 'c1' to the closest integer below (or equal to) a
, and c2
to be the closest integer above it. Then compare the differences. If c1
is closer to a
, set c
to c1
, otherwise c2
.
int c1 = a - (a % b);
int c2 = c1 + b;
int c = a - c1 < c2 - a ? c1 : c2;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With