Double-nested loop with bitwise operation I have this little exercise:

for ( i = 0; i &lt; 2 * n; i += 2 )
  for ( j = 1; j &lt;= n; j &lt;&lt;= 1 )
    if ( j &amp; i )
      foo ();


(j &lt;&lt;= 1 means j = (j &lt;&lt; 1), where &lt;&lt; is the bitwise left shift operator. &amp; is the bitwise and operator.)

I am supposed to determine how many times will the foo function be called for some n. The result should be both an exact number (or the most accurate approximation possible) and asymptotic (like O(n)).
The number of foo() calls is the number of 1 bits in all numbers from 0 to $n$ (or all even numbers between $0$ and $2n$ - same thing). Asymptotically, it's $O(n \log n)$, because the number of 1 bits is around $\log_2(n)/2$.

I don't have an exact function. It won't be a smooth function - for example, $f(1023)-f(1022)=10$, but $f(1024)-f(1023)=1.$