This method is not advisable as it suffers from integer
overflow problems. So use XOR
method to find the two numbers, which is highly performant. If you are interested i can explain.
As per the request from @ordinary below, i am explaining the algorithm:
EDIT
Suppose the maximum element of the array a[]
is B
i.e. suppose a[]={1,2,4}
and here 3
and 5
are not present in a[] so max element is B=5
.
xor
all the elements of the array a
to X
xor
all the elements from 1 to B
to x
- find the left most bit set of
x
by x = x &(~(x-1));
- Now if
a[i] ^ x == x
than xor
a[i]
to p
else xor
with q
- Now for all
k
from 1 to B
if k ^ x == x
than xor
with p
else xor
with q
- Now print
p
and q
proof:
Let a = {1,2,4}
and B
is 5 i.e. from 1 to 5 the missing numbers are 3 and 5
Once we XOR
elements of a
and the numbers from 1 to 5 we left with XOR
of 3 and 5 i.e. x
.
Now when we find the leftmost bit set of x
it is nothing but the left most different bit among 3 and 5. (3--> 011
, 5 --> 101
and x = 010
where x = 3 ^ 5
)
After this we are trying to divide into two groups according to the bit set of x
so the two groups will be:
p = 2 , 2 , 3 (all has the 2nd last bit set)
q = 1, 1, 4, 4, 5 (all has the 2nd last bit unset)
if we XOR
the elements of p
among themselves we will find 3
and similarly if we xor
all the elements of q
among themselves than we will get 5.
Hence the answer.
code in java
public void findNumbers(int[] a, int B){
int x=0;
for(int i=0; i<a.length;i++){
x=x^a[i];
}
for(int i=1;i<=B;i++){
x=x^i;
}
x = x &(~(x-1));
int p=0, q=0;
for(int i=0;i<a.length;i++){
if((a[i] & x) == x){
p=p^a[i];
}
else{
q=q^a[i];
}
}
for(int i=1;i<=B;i++){
if((i & x) == x){
p=p^i;
}
else{
q=q^i;
}
}
System.out.println("p: "+p+" : "+q);
}