Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is binary operation more efficient than modulo?

Tags:

java

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?

like image 389
JavaDeveloper Avatar asked Sep 10 '14 21:09

JavaDeveloper


People also ask

Is modulo 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.

Is Bitwise faster than modulo?

The result was consistent with the idea that bitwise is faster than modulo operator.

Is modulo faster than if?

A modulo-operation is very slow. An if is most likely to be faster than a modulo and more readable.

Is modulo more expensive than division?

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.


2 Answers

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.

like image 137
Robert Harvey Avatar answered Sep 28 '22 05:09

Robert Harvey


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 &.

like image 22
khelwood Avatar answered Sep 28 '22 05:09

khelwood