2

Suppose I have a number $x$, and I want to round $x$ up to the next multiple of $y$ if $x$ isn't already divisible by $y$.

I tried $x + y - (x \mod y)$, but this fails when $x$ is already divisible by $y$. e.g., if $x = 6$ and $y = 3$, then $x + y - (x \mod y) = 9$, but I need it to be $6$ in this situation.

Is there a one line expression that can achieve what I want?

I would like to avoid dealing with non-integers and so do not want to use ceiling and floor functions. I think I would like to restrict the operations to *,/,-,+ and modulo.

24n8
  • 1,455
  • What operations are available to you? $y \lceil x/y \rceil$ will work, but is that “allowed”? – Matthew Leingang Jun 16 '21 at 14:12
  • 1
    @MatthewLeingang Sorry about that. I just edited the OP to be more specific, but I would like to avoid the ceilling and floor functions and just avoid dealing with non-integers in genreal. – 24n8 Jun 16 '21 at 14:13
  • In elementary school, that is called ‘division with remainder’. – Bernard Jun 16 '21 at 14:15

1 Answers1

2

$x+(y-x) \bmod y$ will do the trick if your $\bmod $ function returns a positive quantity even when the starting number is negative.

Ross Millikan
  • 374,822
  • Is it calculator-dependent what a modulo function will do when taking the modulo of a negative number? I've never worked with modulo of negative numbers before. I tried it in some programming languages and it seems some languages return a negative number and others return a positive number. – 24n8 Jun 16 '21 at 14:22
  • I believe it is, but have not tried many. Often $(-6) \bmod 5=-1$. Other times $(-6) \bmod 5 =4$ – Ross Millikan Jun 16 '21 at 14:54