Floor
How do you compute โ๐ฅ+๐ฆ2โ without overflow in ๐ฅ+๐ฆ ?
We can decompose the addition into two parts, an addition with carries ignored (XOR) and one with the carries, shifted into place:
- ๐ฅ+๐ฆ=(๐ฅโ๐ฆ)+((๐ฅย &ย ๐ฆ)โช1)
We shift right by one on both sides, cancelling out the shift left:
- (๐ฅ+๐ฆ)โซ1=((๐ฅโ๐ฆ)โซ1)+(๐ฅย &ย ๐ฆ)
Ceiling
If you want to calculate โ๐ฅ+๐ฆ2โ however, we can use a different, more exciting identity for addition that uses subtraction:
- ๐ฅ+๐ฆ=((๐ฅย |ย ๐ฆ)โช1)โ(๐ฅโ๐ฆ)
And then after shifting right by one on both sides we are left with:
- (๐ฅ+๐ฆ)โซ1=(๐ฅย |ย ๐ฆ)โ((๐ฅโ๐ฆ)โซ1)
This goes to the ceiling because we are flooring the part we are subtracting via the right shift.
Uh, where did that new subtraction based identity come from?
Working backwards towards another well known identity, if we spell out the left shift with addition we get:
- ๐ฅ+๐ฆ=(๐ฅย |ย ๐ฆ)+(๐ฅย |ย ๐ฆ)โ(๐ฅโ๐ฆ)
Then using the following identity for exclusive or:
- ๐ฅโ๐ฆ=(๐ฅย |ย ๐ฆ)โ(๐ฅย &ย ๐ฆ)
We get the following, being careful with the sign:
- ๐ฅ+๐ฆ=(๐ฅย |ย ๐ฆ)+(๐ฅย |ย ๐ฆ)โ(๐ฅย |ย ๐ฆ)+(๐ฅย &๐ฆ)
Or:
- ๐ฅ+๐ฆ=(๐ฅย |ย ๐ฆ)+(๐ฅย &ย ๐ฆ)
Source
Hacker's Delight, Dietz, and HAKMEM. Using pommicket's LaTeX tool, which I wanted an excuse to try.
this is my first post
