Count pairs with Odd XOR

Given an array of n integers. Find out number of pairs in array whose XOR is odd.

Examples:

```Input : arr[] = { 1, 2, 3 }
Output : 2
All pairs of array
1 ^ 2 = 3
1 ^ 3 = 2
2 ^ 3 = 1

Input : arr[] = { 1, 2, 3, 4 }
Output : 4```

Naive Approach: We can find pairs whose XOR is odd by running two loops. If XOR of two number is odd increase count of pairs.

`// C++ program to count pairs in array `
`// whose XOR is odd`
`#include <iostream>`
`using` `namespace` `std;`
`// A function will return number of pair `
`// whose XOR is odd`
`int` `countXorPair(``int` `arr[], ``int` `n)`
`{`
`    ``// To store count of XOR pair`
`    ``int` `count = 0;`
`    `
`    ``for` `(``int` `i = 0; i < n; i++)`
`    ``{`
`        ``for` `(``int` `j = i+1; j < n; j++)`
`          ``// If XOR is odd increase count`
`          ``if` `((arr[i] ^ arr[j]) % 2 == 1)`
`              ``count++;`
`    ``}`
`    `
`    ``// Return count`
`    ``return` `count;`
`}`
`// Driver program to test countXorPair()`
`int` `main()`
`{`
`    ``int` `arr[] = { 1, 2, 3 };`
`    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr[0]);`
`    ``cout << countXorPair(arr, n);`
`    ``return` `0;`
`}`

Output:

```2
```

Time Complexity : O(n*n)

Efficient Approach: We can observe that:

```odd ^ odd = even
odd ^ even = odd
even ^ odd = odd
even ^ even = even
```

Therefore total pairs in array whose XOR is odd will be equal to count of odd numbers multiplied by count of even numbers.

`// C++ program to count pairs in array `
`// whose XOR is odd`
`#include <iostream>`
`using` `namespace` `std;`
`// A function will return number of pair`
`//  whose XOR is odd`
`int` `countXorPair(``int` `arr[], ``int` `n)`
`{`
`    ``// To store count of odd and even `
`    ``// numbers`
`    ``int` `odd = 0, even = 0;`
`    `
`    ``for` `(``int` `i = 0; i < n; i++)`
`    ``{`
`        ``// Increase even if number is`
`        ``// even otherwise increase odd`
`        ``if` `(arr[i] % 2 == 0)`
`            ``even++;`
`        ``else`
`            ``odd++;`
`    ``}`
`    `
`    ``// Return number of pairs`
`    ``return` `odd * even;`
`}`
`// Driver program to test countXorPair()`
`int` `main()`
`{`
`    ``int` `arr[] = { 1, 2, 3 };`
`    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr[0]);`
`    ``cout << countXorPair(arr, n);`
`    ``return` `0;`

Output:

```2
```

Time Complexity : O(n)

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits:http://www.geeksforgeeks.org/count-pairs-odd-xor/
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at