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 !!!
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 !!!
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