Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closest divisible integer

Tags:

java

math

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.

like image 266
ThatGuy343 Avatar asked Apr 05 '15 03:04

ThatGuy343


2 Answers

There are two cases to consider:

  1. The closest integer that is less than or equal to a:

    int c1 = a - (a % b);
    
  2. 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
like image 200
Anderson Vieira Avatar answered Sep 20 '22 17:09

Anderson Vieira


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;
like image 41
Mshnik Avatar answered Sep 20 '22 17:09

Mshnik