I am trying to find out the number of 1's in binary form of a large decimal number (decimal number can be as large as 1000000).
I tried this piece of code:
while(sum>0)
{
if(sum%2 != 0)
{
c++; // counting number of ones
}
sum=sum/2;
}
I want a faster algorithm as it takes long time for large decimal input. Please suggest me an efficient algorithm.
using right bit shift operator
If you apply the AND operation to the integer and the result of the subtraction, the result is a new number that is the same as the original integer except that the rightmost 1 is now a 0. For example,01110000 AND (01110000 – 1) = 01110000 AND 01101111 = 01100000.
This solution has a running time of O(m), where m is the number of 1s in the solution.
In C++ you can just do this.
There are many ways. Easy to understand and quite fast is Brian Kernighan's way :
What you are looking for is "popcount", which is implemented as a single CPU instruction on later x64 CPU's, which won't be beaten for speed:
But of course, you'll need to test the CPU supports it first:
Here's an implementation in C:
The GNU C Compiler runtime contains a "built-in" which might be faster than the implementation above (it might use the CPU popcnt instruction, but that's implementation-specific):
All of the above implementations are used in my C++ chess library as popcount plays a vital role in chess move generation when bitboards are used to represent piece positions. I use a function pointer, set-up during library initialisation, to point to the implementation requested by the user and then use the popcount function via that pointer.
Google will provide many other implementations as it's an interesting problem, for example: http://wiki.cs.pdx.edu/forge/popcount.html.