1

We need to find ordered pairs (a,b).

(2<=s<=10^12) and (0<=x<=10^12)

For example -

s=9 x=5 We have number of ordered pairs = 4{(2,7),(7,2)(3,6)(6,3)}

Can someone please provide me a method to solve this question !!!

user3111412
  • 177
  • 1
  • 3
  • 11
  • Note that a + b = 2 * (a & b) + (a ^ b) = 2 * (a | b) - (a ^ b), by definition of the sum-bit and carry-bit computations in integer addition. – njuffa Mar 27 '16 at 19:16
  • Contest question ([Cross reference](http://codeforces.com/problemset/problem/627/A)) – njuffa Mar 27 '16 at 19:37
  • Thanks @njuffaa, actually i know this definition. I am stuck after this. If you know further how to solve can you please explain the steps. – user3111412 Mar 28 '16 at 10:23
  • 2
    Possible duplicate of [Given XOR & SUM of two numbers. How to find the numbers?](http://stackoverflow.com/questions/18732329/given-xor-sum-of-two-numbers-how-to-find-the-numbers) – Spektre Mar 29 '16 at 07:26

1 Answers1

3

Here is the logic let the numbers be a and b, we know

s = a + b
x = a ^ b

therefore

x = (s-b) ^ b

Since we know x and we know s, so for all ints going from 0 to s - just check if this last equation is satisfied

here is the code for this

public List<Pair<Integer>> pairs(int s, int x) {
    List<Pair<Integer>> pairs = new ArrayList<Pair<Integer>>();
    for (int i = 0; i <= s / 2; i++) {
        int calc = (s - i) ^ i;
        if (calc == x) {
            pairs.add(new Pair<Integer>(i, s - i));
            pairs.add(new Pair<Integer>(s - i, i));
        }
    }
    return pairs;
}

Class pair is defined as

class Pair<T> {
    T a;
    T b;

    public String toString() {
        return a.toString() + "," + b.toString();
    }

    public Pair(T a, T b) {
        this.a = a;
        this.b = b;
    }
}

Code to test this:

public static void main(String[] args) {
    List<Pair<Integer>> pairs = new Test().pairs(9,5);
    for (Pair<Integer> p : pairs) {
        System.out.println(p);
    }
}

Output:

2,7
7,2
3,6
6,3
abhaybhatia
  • 599
  • 1
  • 7
  • 16
  • Thanks @abhaybhatia, but dont you think it will take a lot of time when 's' will be 10^12. As we are running the loop whole from 1 till s/2. – user3111412 Mar 31 '16 at 08:47