Line 294 of java.util.Random source says
if ((n & -n) == n) // i.e., n is a power of 2 // rest of the code
Why is this?
(archaic) Contraction of if and when.
In addition, we have some variations of these basic styles of proofs. Definition: An integer n is called even if and only if there exists an integer k such that n=2k. An integer n is called odd if and only if there exists an integer k such that n=2k+1. Theorem: If n is an odd integer, then n2 is an odd integer.
Because in 2's complement, -n
is ~n+1
.
If n
is a power of 2, then it only has one bit set. So ~n
has all the bits set except that one. Add 1, and you set the special bit again, ensuring that n & (that thing)
is equal to n
.
The converse is also true because 0 and negative numbers were ruled out by the previous line in that Java source. If n
has more than one bit set, then one of those is the highest such bit. This bit will not be set by the +1
because there's a lower clear bit to "absorb" it:
n: 00001001000 ~n: 11110110111 -n: 11110111000 // the first 0 bit "absorbed" the +1 ^ | (n & -n) fails to equal n at this bit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With