2

According to this post Performance of doing bitwise operations on bitsets performance is O(n) how do I make it O(log n). Thanks.

moghya
  • 854
  • 9
  • 18
  • I'd say it depends. You will have to provide more info. A O(1) solution for `std::bitset<8>` is entirely possible I think, but not for `std::bitset<2048>`. – Rakete1111 Jun 13 '17 at 11:24
  • 1
    You cannot do bitwise operation on bitsets of size O(n) in less than O(n) operations – DAle Jun 13 '17 at 11:29
  • Unless we have a [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) here, you cannot do that. – yeputons Jun 13 '17 at 11:34
  • Whether you can do it depends on your computational model, but that may be considered "cheating". Eg in the PRAM model it's easy. – harold Jun 13 '17 at 11:54

1 Answers1

7

The answer is you don't.

Assume you have a bitset of n size. Let's look at the xor operator ^. It obviously has to look at each bit in both operands, so it makes 2n lookups. This results in a complexity of O(n).

You can use assembler instructions that e.g. do it for 32 bits at a time, so the number of operations is (n+31)/32, but this doesn't change that the complexity is O(n). After all complexity is calculated for n towards infinity and constant factors are disregarded.

Adder
  • 5,708
  • 1
  • 28
  • 56