Codeforce - 1748D (ConstructOR)

Codeforce - 1748D (ConstructOR)

Jan 04, 2023

First, let's check the impossible case.
Impossible case : Let, lsb(x) be the position of the first bit from right which is set. Now, if lsb(a) < lsb(d) or lsb(b) < lsb(d) then it is impossible to find any x.
prove : If Temp is any number and Val is divided by Temp. So, we can represent Val by Val = Temp x X.
Val = Temp x (2 ^ 30 x i30 + .... + 2^1 x i1 + 2^0 x i0)
Val = Temp x 2 ^ 30 x i30 + ......
Here, multiplying Temp with 2 ^ k means left shifting Temp by k bits. That means, If Val is divided by Temp then lsb(Val) >= lsb(Temp).

Now, Let's make F = a | b. Because, I want to simplify the problem and wants to find a X such that a | X = b | X = X (or F | X = X) and X is divisible by d. So, let's find a multiple of d (X) for which a | X = b | X = X ( This means that if ith bit of A is set or ith bit of B is set then ith bit of X must be set).

Initially X = D. Lets iterate over all bits of (A | B) = F. Now, there could be 4 case for ith bit :
Fi is 0 and Xi is 0 : Nothing to do as both of them is 0.
Fi is 1 and Xi is 1 : Nothing to do as both of them is 1.
Fi is 0 and Xi is 1 : Nothing to do as still F | X = X (remind : X is my final answer) and nothing changed in X and so X is divisible by D.
Fi is 1 and Xi is 0 : Now, F | X != X. I have to set Xi to 1 such that X is still divisible by D. Let the new answer be X'. We know if temp is divisible by d then (temp + d * temp1) is also divisible by d. So, if I can add a multiple of D with X ( X' = X + temp x D) then X' is divisible by D (as X is divisible by D). Now, I have to choose temp such that X'i bit is 1. We know, multiplying 2^k with a value means shifting that value to the left k numbers of time. So, let's take temp = 2^k such that the first set value of D comes to the position of ith bit. Finally , X' = X + 2^k x D where k = i - position of first set bit of D.
So, X = X' and check the next bits.

X is now my final answer :)

Enjoy this post?

Buy Tanzim Bin Nasir a keyboard

More from Tanzim Bin Nasir