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.
F(n)
Complexity should be O(log n)
O(log n)
If n= 2^k-1, then F(n)=k*(n+1)/2
n= 2^k-1, then F(n)=k*(n+1)/2
For a general n, let m be the largest number such that m = 2^k-1 and m<=n. F(n) = F(m) + F(n-m-1) + (n-m).
n
m
m = 2^k-1
m<=n
F(n) = F(m) + F(n-m-1) + (n-m)
Corner condition: F(0)=0 and F(-1)=0.
F(0)=0
F(-1)=0