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
.
Advertisement
Answer
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