Find closest possible integer such that a/b is an integer

74 Views Asked by At

I have $a/b$ ($b$ is an integer but may not matter).

I want $a/b\prime$ to be an integer by leaving $a$ and choosing an integer $b\prime$ that is closest to $b$.

If it would be the other way round (choosing integer $a\prime$ closest to $a$) then the solution is simply

$$ a\prime = \operatorname{round}(a/b) b $$

This should be trivial but I am somewhat stuck. I played around applying the usual candidates (round, floor, gcd, mod).

1

There are 1 best solutions below

1
On BEST ANSWER

I presume $a$ is an integer, otherwise there is no such $b'$. In order to have $a/b'$ an integer, you need $b'$ to be a divisor of $a$. So find the divisors of $a$, and take $b'$ to be either the least divisor greater than $b$ or the greatest divisor less than $b$, whichever is closer.