in reply to Best way to make sure a number is an even multiple of another?

Just for the record:
sub fix { my($n, $m) = @_; $n + ($n*$m - $n)%$m; }
  • Comment on Re: Best way to make sure a number is an even multiple of another?
  • Download Code

Replies are listed 'Best First'.
Re^2: Best way to make sure a number is an even multiple of another?
by Roy Johnson (Monsignor) on Oct 21, 2004 at 14:37 UTC
    What's your rationale for the multiplication? It seems to work fine with "$n*" deleted.

    Caution: Contents may have been coded under pressure.
      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.

        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.