1. Sequential Popcount Summation
Intuition
Initialize total = 0. For every integer i from 1 to n, count its set bits using val &= (val - 1) and add to total.
When to apply: Verification for small n (n <= 105).
Algorithm
- Step 1: Set total = 0.
- Step 2: Loop i from 1 to n.
- Step 3: Count set bits of i and add to total.
- Step 4: Return total.
#include <iostream> using namespace std; long long countTotalSetBitsBrute(int n) { long long total = 0; for (int i = 1; i <= n; ++i) { int temp = i; while (temp > 0) { temp &= (temp - 1); total++; } } return total;} int main() { cout << "Brute (4): " << countTotalSetBitsBrute(4) << endl; // 5 cout << "Brute (7): " << countTotalSetBitsBrute(7) << endl; // 12 return 0;}Time & Space Complexity
- Time complexity:
O(n log n) - Space complexity:
O(1)