1
+ '''
2
+
3
+ Aim: Given set S = {1,2,3,....,N}. Find two integers, I and J (where I<J),
4
+ from set S such that the value of I & J is the maximum possible and also
5
+ less than a given integer, K. In this case, '&' represents the bitwise AND
6
+ operator.
7
+
8
+ Input Format:
9
+ 1. The first line contains an integer T, the number of test cases.
10
+ 2. Each of the T subsequent lines defines a test case as 2 space-separated
11
+ integers, N and K, respectively.
12
+
13
+ '''
14
+
15
+ def max_bit (n ,k ):
16
+ maximum = 0 # we need a counter to keep a check on the value of I & J, it should not exceed K
17
+ for i in range (1 ,n + 1 ):
18
+ for j in range (1 ,i ):
19
+ h = i & j # storing bitwise AND value in a variable h
20
+ if maximum < h < k : # I & J < K
21
+ maximum = h
22
+ if maximum == k - 1 : # if maximum becomes equal to k-1, we have found the maximum value of I & J which will be less than K
23
+ return maximum
24
+ return maximum
25
+
26
+ if __name__ == '__main__' :
27
+ t = int (input ())
28
+ for t_itr in range (t ):
29
+ nk = input ().split ()
30
+ n = int (nk [0 ]) # getting the value of N
31
+ k = int (nk [1 ]) # getting the value of K
32
+ print (max_bit (n ,k )) # calling function to compute the answer
33
+
34
+ '''
35
+
36
+ Sample Test Case:
37
+ Input:
38
+ 3
39
+ 5 2
40
+ 8 5
41
+ 2 2
42
+ Output:
43
+ 1
44
+ 4
45
+ 0
46
+ Explaination:
47
+ N = 5, K = 2, S = {1,2,3,4,5}
48
+ All possible values of I and J are:
49
+ 1. I = 1, J = 2; I & J = 0
50
+ 2. I = 1, J = 3; I & J = 1
51
+ 3. I = 1, J = 4; I & J = 0
52
+ 4. I = 1, J = 5; I & J = 1
53
+ 5. I = 2, J = 3; I & J = 2
54
+ 6. I = 2, J = 4; I & J = 0
55
+ 8. I = 2, J = 5; I & J = 0
56
+ 9. I = 3, J = 5; I & J = 1
57
+ 10. I = 4, J = 5; I & J = 4
58
+ The maximum possible value of I & J that is also < (K = 2) is 1, so the output will be 1.
59
+
60
+ '''
0 commit comments