ProgrammingHardGATE CS · Competitive coding (CP)

How many integers n with 1 <= n <= 64 satisfy both (n & (n - 1)) == 0 and (n & 0x55555555u) != 0? Compute with this program.

How many integers n with 1 <= n <= 64 satisfy both (n & (n - 1)) == 0 and (n & 0x55555555u) != 0? Compute with this program.
#include <stdio.h>
int main(void) {
    int c = 0;
    for (unsigned n = 1; n <= 64; n++)
        if ((n & (n - 1)) == 0 && (n & 0x55555555u) != 0) c++;
    printf("%d", c);
}
  1. A. 3
  2. B. 5
  3. C. 6
  4. D. 4

Correct answer: D. 4

The first test keeps the powers of two, and the mask keeps those whose only set bit is at an even position. The qualifying values are 1, 4, 16 and 64, which gives 4.

More C Programming questions

Exams that ask this topic