I know how to find out how many bits are on in a given number (or how many elements are true in a boolean arra), using a mask and bitwise operators, going over all bits checking if they are on. Assuming the number is of arbitrary length, the algorithm runs in O(n) time, where n is the number of bits in the number. Is there an asymptotically better algorithm? I don’t think that’s possible, but how can I formally prove it?
Share
I think the type of formality you’re looking for is an “adversarial proof”.
Suppose one has an algorithm A that runs faster than O(n). Then for sufficiently large n, A must not look at some bit i. We then claim that A must be incorrect. An “adversary” will give A two strings s1 and s2 that are identical except for opposite values of bit i. The algorithm A will return the same value for s1 and s2, so the adversary has “tricked” A into giving the wrong answer. So no correct algorithm A running in o(n) time exists.