Bit manipulation involving and operator


Given a special function

F(X,Y,Z) = (X ∧ Z)⋅(Y ∧ Z) where ∧ is bitwise AND operator; X,Y,Z are non-negative integers; and ‘.’ represents product

We want to maximize the function F(X,Y,Z) for given X and Y by choosing an appropriate Z. Additionally we have been given limits L and R for Z

To summarize, we need to find a non-negative integer Z (L≤Z≤R) such that F(X,Y,Z) = maxL ≤ k ≤ R(F(X,Y,k)) If there is more than one such value of Z, we should find the smallest one in the range [L,R]

Note: X, Y, L and R are chosen in such a way that maxL≤k≤R(F(X,Y,k)) never exceeds 262

Example: For X, Y, L, R = 7, 12, 4, 17 respectively, answer = 15

I understand the problem, but need help to find an optimal solution for this.