There are two ways to check if the number is divisible by 2:
x % 2 == 1
(x & 1) == 1
Which of the two is more efficient?
Modular exponentiation can be performed with a negative exponent e by finding the modular multiplicative inverse d of b modulo m using the extended Euclidean algorithm. That is: c = be mod m = d−e mod m, where e < 0 and b ⋅ d ≡ 1 (mod m). Modular exponentiation is efficient to compute, even for very large integers.
The result was consistent with the idea that bitwise is faster than modulo operator.
A modulo-operation is very slow. An if is most likely to be faster than a modulo and more readable.
Apparently doing modulus by power of two means just like looking at last n bits. Show activity on this post. Modulo operator is expensive but the division is expensive too. So converting your code from using modulo operator to division is not going to optimize your code.
The bit operation is almost certainly faster.
Division/modulus is a generalized operation which must work for any divisor you provide, not just 2. It must also check for underflow, range errors and division by zero, and maintain a remainder, all of which takes time.
The bit operation just does a bit "and" operation, which in this case just so happens to correspond to division by two. It might actually use just a single processor operation to execute.
Either the &
expression will be faster or they will be the same speed. Last time I tried, they were the same speed when I used a literal 2 (because the compiler could optimise it) but %
was slower if the 2
was in a variable.
The expression x % 2 == 1
as a test for odd numbers does not work for negative x
.
So there's at least one reason to prefer &
.
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