buf[0] = 0; int p = 1; int s = 1; do { for (int i = p; i < p * 2; ++i) buf[i] = buf[i - p] + 1; p *= 2; s += p; } while (s <= N);