C program to find out the maximum value of AND, OR, and XOR operations that are less than a given value

Suppose we are given two integers k and n. Our task is to perform three operations; bitwise AND, bitwise OR, and bitwise XOR between all pairs of numbers up to range n. We return the maximum value of all three operations between any two pairs of numbers that is less than the given value k.

So, if the input is like n = 5, k = 5, then the output will be 4 3 4.

The greatest value of AND, OR, and XOR operations between all pairs of numbers that are less than 5 are 4, 3, and 4 respectively. We can see that the values of these operations are less than that of the given value k, which is 5.

Syntax

void findMaxOperations(int n, int k);
// Find maximum AND, OR, XOR values less than k for pairs (i,j) where 1 ? i < j ? n

Algorithm

To solve this, we will follow these steps −

  • andMax := 0, orMax = 0, xorMax = 0
  • For all pairs (i, j) where i
  • Calculate value1 := i AND j
  • Calculate value2 := i OR j
  • Calculate value3 := i XOR j
  • Update maximum values if they are less than k

Example

Let us see the following implementation to get better understanding −

#include <stdio.h>

void solve(int n, int k) {
    int andMax = 0, orMax = 0, xorMax = 0;
    int value1 = 0, value2 = 0, value3 = 0;
    
    for (int i = 1; i <= n; i++) {
        for (int j = i + 1; j <= n; j++) {
            value1 = i & j;
            value2 = i | j;
            value3 = i ^ j;
            
            if (value1 > andMax && value1 < k)
                andMax = value1;
            if (value2 > orMax && value2 < k)
                orMax = value2;
            if (value3 > xorMax && value3 < k)
                xorMax = value3;
        }
    }
    printf("AND: %d, OR: %d, XOR: %d<br>", andMax, orMax, xorMax);
}

int main() {
    int n = 5, k = 5;
    printf("Finding maximum bitwise operations for n=%d, k=%d<br>", n, k);
    solve(n, k);
    return 0;
}
Finding maximum bitwise operations for n=5, k=5
AND: 4, OR: 4, XOR: 4

How It Works

The algorithm checks all possible pairs (i, j) where i

Key Points

  • The time complexity is O(n²) as we check all pairs.
  • We only consider pairs where i
  • Each operation result must be less than k to be considered valid.

Conclusion

This approach efficiently finds the maximum values of bitwise AND, OR, and XOR operations between pairs of numbers in a given range while ensuring the results remain below a specified threshold.

Updated on: 2026-03-15T14:25:50+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements