Bit complement operator in the Euclidean division

https://math.stackexchange.com/questions/679146/euclidean-divison-program

did not respond to this request.

I learned that, given the two integers a and b, with b ≠ 0, there are unique integers q and r such that a = bq + r and 0 ≤ r <| b |, where | b | denotes the absolute value of the b-definition of Euclidean division

The corresponding program that implements this logic is shown below:

int ifloordiv(int n, int d){

if (n >= 0)
    return n / d;
else
    return ~(~n / d);
}

After reading the code above, it is obvious to me that I understand that (n> = 0) {} is the logic of the block code, that we are doing real division, not Euclidean.

But, else {(n <0)} the logic of the code using the bit complement operator (~) did not seem obvious to me in order to understand the thinking approach using the ~ operator. Usually we use the → operator when we think about division.

, java ~ 1 .

:

, (~), n < 0. ~. , .

+3
1

~n -n - 1.

So ~(~n / d) - -((-n - 1) / d) - 1.

n d , ( , n). , .

+6

All Articles