/* * pvector_get_array_spec -- (internal) translates a global vector index * into a more concrete position in the array. */ static struct array_spec pvector_get_array_spec(uint64_t idx) { struct array_spec s; /* * Search for the correct array by looking at the highest bit of the * element position (offset by the size of initial array), which * represents its capacity and position in the array of arrays. * * Because the vector has large initial embedded array the position bit * that was calculated must take that into consideration and subtract * the bit position from which the algorithm starts. */ uint64_t pos = idx + PVECTOR_INIT_SIZE; unsigned hbit = find_highest_bit(pos); s.idx = (size_t)(hbit - PVECTOR_INIT_SHIFT); /* * To find the actual position of the element in the array we simply * mask the bits of the position that correspond to the size of * the array. In other words this is: pos - 2^[array index]. */ s.pos = pos ^ (1ULL << hbit); return s; }
int main(int argc, char** argv) { if (argc < 2) { printf("Usage: %s <a-positive-number-N>\n", argv[0]); printf("Imagine the numbers [0..N-1] written out in sequence one below another forming a matrix.\n"); printf("Each number is written in its binary representation.\n"); printf("Thus, if N is 5, the numbers are written as:-\n"); printf("000\n001\n010\n011\n100\n"); printf("This routine prints the number of 1's in each of the three columns, \n" "with column number 0 representing the least significant bit.\n"); printf("So, the answer will be for N=5, (1,2,2) indicating that at column number 2, 1 and 0, there\n" "are 1, 2 and 2 one's respectively\n"); return 1; } unsigned int n = atoi(argv[1]); unsigned int highest_bit = find_highest_bit(n-1); printf ("Highest bit for N=%u is %u\n", n, highest_bit); unsigned i = highest_bit; while (1) { unsigned Ni = n / two_raised_to(i+1); unsigned Ri = n % two_raised_to(i+1); unsigned nr_ones = (Ni * two_raised_to(i)) + (Ri > two_raised_to(i) ? (Ri - two_raised_to(i)) : 0); printf("Column %u: %u\n", i, nr_ones); if (i==0) break; i --; } return 0; }