Search code examples
cbitwise-operators

Code containing bitwise operators fails test cases


I have the task:

Given set S = {1,2,3,..., n}, find:

  • the maximum value of a&b which is less than a given integer k, where a and b (where a < b) are two integers from set S.

  • the maximum value of a|b which is less than a given integer k, where a and b (where a < b) are two integers from set S.

  • the maximum value of a^b which is less than a given integer k, where a and b (where a < b) are two integers from set S.

My code doesn't work although I can't find a mistake

There's the following test case:

Input: 5 4

Output:

2
3
3

However my output is:

1382045904
24
3

My code:

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

void calculate_the_maximum(int n, int k) {
    int max_and, max_or, max_xor = -1;

    for (int a = 0; a < n; a++) {
        for (int b = a + 1; b <= n; b++) {
            int currently_and = a & b, currently_or = a | b, currently_xor = a ^ b;

            if ((max_and < currently_and) && (currently_and < k)) {
                max_and = currently_and;
            }
            if ((currently_or > max_or) && (currently_or < k)) {
                max_or = currently_or;
            }
            if ((currently_xor > max_xor) && (currently_xor < k)) {
                max_xor = currently_xor;
            }
        }
    }

    printf("%d\n%d\n%d\n", max_and, max_or, max_xor);
}


Solution

  • max_and and max_or are not initialized in your code, so they contain garbage values.

    More specifically,

      int max_and, ...
      for(int a = 0; a < n; a++){
          for(int b = a + 1; b <= n; b++){
              int currently_and = a & b, currently_or = a | b, currently_xor = a ^ b;
              if ((max_and < ...
    

    tries to read from max_and before it has been set. This accesses an indeterminate value, so the code has undefined behavior.