in reply to Re^3: Best way to make sure a number is an even multiple of another?
in thread Best way to make sure a number is an even multiple of another?

I think, then, that you want
$n + ($m - $n % $m) % $m;
That ensures that what you are subtracting from $m is not larger than $m, and the result is the same, modulo $m.

In Perl, modulo works as it is supposed to. :-) The result is between zero and the right operand. In Java, it's broken. This allows us to simplify the expression a bit further:

$n + -$n%$m;

Caution: Contents may have been coded under pressure.

Replies are listed 'Best First'.
Re^5: Best way to make sure a number is an even multiple of another?
by hv (Prior) on Oct 22, 2004 at 10:44 UTC

    The modulo operator works as I'd expect as long as you don't use integer; as soon as you do, you are at the mercy of your C implementation, which I believe is likely to vary between machines.

    On this Linux machine, for example:

    zen% perl -le 'print -1 % 3' 2 zen% perl -Minteger -le 'print -1 % 3' -1 zen%

    If you're happy to rely on it, the original request to get the least multiple of $m >= $n can be satisfied by: $n + ((-$n) % $m).

    Hugo