Finding the total number of set-bits from 1 to n

后端 未结 16 2099
轻奢々
轻奢々 2020-12-04 09:54

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)

16条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-04 10:17

    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)
    

提交回复
热议问题