Bronson wrote On 06/28/07 17:40,:
Hi,
i'm looking for a fast way to find greatest multiple of a, which is
smaller than b.
Recently i've used b-b%a, but maybe it could be done faster.
(Assumptions: a and b are integers, a positive and b non-
negative.)
The formula you're using doesn't solve the problem you've
described. For example, consider a=3, b=12: your formula
yields 12, which is not smaller than b.
To solve the problem stated, you could use (b-1)-(b-1)%a.
If a is known to be a power of two, you can replace the
mod operation with an and: (b-1)-((b-1)&(a-1)). It is tempting
to simplify this even further to (b-1)&~(a-1), but this is
completely safe only if a is an unsigned integer; applying ~
to a signed integer has non-portable consequences. A possible
alternative that works for signed integers is ((b-1)|(a-1))^(a-1),
but that seems no better than the first and-ing formula.