in reply to Re^2: 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 don't trust modulo on a negative number. I'm never sure what value -2 % 5 will have. 3 or -2? I believe it depends on the language.

So, I want an easy, reliable way to add a multiple ($i) of $m so that $i - $n >= 0. The exact number doesn't matter, as

($r*$m + $s) % $m == $s % $m
for any non-negative integers $r and $s, and positive integer $m.

$m*$n is both a multiple of $m, and at least as large as $n.

Replies are listed 'Best First'.
Re^4: Best way to make sure a number is an even multiple of another?
by Roy Johnson (Monsignor) on Oct 21, 2004 at 16:39 UTC
    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.

      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