Write an algorithm to find F(n) the number of bits set to 1, in all numbers from 1 to n for any given value of n.
Complexity should be O(log n)
A quick search for the values of the sequence F lead to this integer sequence http://oeis.org/A000788
There I spotted a formula: a(0) = 0, a(2n) = a(n)+a(n-1)+n, a(2n+1) = 2a(n)+n+1 (a is the same as F since I just copy the formula from oeis)
which could be used to compute a(n) in log(n).
Here's my sample C++ code:
memset(cache, -1, sizeof(cache))
cache[0] = 0
int f(int n)
if cache[n] != -1 return cache[n];
cache[n] = n % 2 ? (2 * f(n / 2) + n / 2 + 1) : (f(n / 2) + f(n / 2 - 1) + n / 2)