Integer division that rounds up: Difference between revisions
From wikiluntti
(→Proof) |
(→Proof) |
||
Line 29: | Line 29: | ||
'''Part 2'''. If <math>y</math> does not divide <math>x</math> we have <math>x=by + r</math> for some <math>b\in\mathbb N_+</math> and <math>0<r<b-1</math>. Thus we have | '''Part 2'''. If <math>y</math> does not divide <math>x</math> we have <math>x=by + r</math> for some <math>b\in\mathbb N_+</math> and <math>0<r<b-1</math>. Thus we have | ||
<math> | |||
\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 \\ | |||
&= | |||
\end{align} | |||
</math> |
Revision as of 11:12, 8 July 2024
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