Integer division that rounds up

From wikiluntti
Revision as of 11:18, 8 July 2024 by Mol (talk | contribs) (→‎Proof)

Introduction

Usual integer division rounds down: for . To round up (if overflow is not an issue), you can use following algorithm with the usual roundig down division:

Proof

Proof is in two parts; 1st if divides , and if not. Note that usual integer division rounds down.

Part 1. If divides we have for some . Thus we have

because . This part is ok.

Part 2. If does not divide we have for some and . Thus we have

Failed to parse (SVG (MathML can be enabled via browser plugin): Invalid response ("Math extension cannot connect to Restbase.") from server "https://wikimedia.org/api/rest_v1/":): {\displaystyle \begin{align} \left \lfloor \frac{x+y-1}{y} \right \rfloor &= \left \lfloor \frac{x}{y} + \frac{y-1}y \right \rfloor \\ &= \left \lfloor \frac{by+r}{y} + \frac{y-1}y \right \rfloor \\ &= \left \lfloor \frac{by}{y} + \frac ry + \frac yy - \frac 1y \right \rfloor \\ &= \left \lfloor \frac{by + y}{y} + \frac {r-1}y \right \rfloor \\ &= \left \lfloor \frac{(1+y)b}{y} + \frac {r-1}y \right \rfloor \\ \end{align} }