###scala:
scala:
@tailrec
def bits (i: Long, sofar: Int): Int = if (i==0) sofar else bits (i >> 1, (1 & i).toInt + sofar)
computes on a 2Ghz single core for about 1.500.000 64bit Long values the number of bits set.
A straight forward recursive method, comparing the last bit, and shifting the number towards zero. The @tailrec
is just a hint to the compiler to warn me, if it can't optimize the tail recursive call - it is not necessary, for the optimization to take place.
It's about 10times faster than the simplest method, using the library function:
def f(n:Long)=n.toBinaryString.count(_=='1')
Translating them to c++ might not lead to similar results.