Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For given two integers A and B, find a pair of numbers X and Y such that A = X*Y and B = X xor Y

Tags:

I'm struggling with this problem I've found in a competitive programming book, but without a solution how to do it.

For given two integers A and B (can fit in 64-bit integer type), where A is odd, find a pair of numbers X and Y such that A = X*Y and B = X xor Y. My approach was to list all divisors of A and try pairing numbers under sqrt(A) with numbers over sqrt(A) that multiply up to A and see if their xor is equal to B. But I don't know if that's efficient enough. What would be a good solution/algorithm to this problem?

like image 206
Aster W. Avatar asked Nov 23 '19 17:11

Aster W.


People also ask

How do you find 2 numbers when their XOR is given?

A simple solution is to generate all possible pairs with given XOR. To generate all pairs, we can follow below rules. If X[i] is 1, then both a[i] and b[i] should be different, we have two cases. If X[i] is 0, then both a[i] and b[i] should be same.

What is XOR of two numbers?

XOR or eXclusive OR is a logical operation that compares the input values (bits) and generates the output value (bit). The exclusive OR logic is very simple. If the input values are the same, the output is 0 (or false). If the input values are different, the result is 1 (or true).


1 Answers

You know that at least one factor is <= sqrt(A). Let's make that one X.

The length of X in bits will be about half the length of A.

The upper bits of X, therefore -- the ones higher in value than sqrt(A) -- are all 0, and the corresponding bits in B must have the same value as the corresponding bits in Y.

Knowing the upper bits of Y gives you a pretty small range for the corresponding factor X = A/Y. Calculate Xmin and Xmax corresponding to the largest and smallest possible values for Y, respectively. Remember that Xmax must also be <= sqrt(A).

Then just try all the possible Xs between Xmin and Xmax. There won't be too many, so it won't take very long.

like image 144
Matt Timmermans Avatar answered Oct 19 '22 05:10

Matt Timmermans