Odd Multiplicity
National Olympiad — National round
Submission name: odd.cpp
Problem summary
Exactly one value occurs an odd number of times in the given sequence; every other value occurs an even number of times. Find it.
Input
Odd N, followed by N positive integers.
Output
The value of odd multiplicity.
Constraints
2 < N < 1,000,000; values 1…10¹³.
Worked example
An independently prepared example for this explanation.
Input
5 8 2 8 2 8
Output
8
Solution analysis
- XOR all values into a 64-bit accumulator.
Why it works
Equal values cancel in pairs because x XOR x=0. The single unpaired value remains.
Watch out. 32-bit integers cannot hold the allowed values.
Commented C++17 solution
An independently written complete program with standard headers.
// Key idea: Equal values cancel in pairs because x XOR x=0. The single unpaired value remains.
#include<iostream>
#include<tuple>
using namespace std;
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin>>n;
long long ans=0,x;
while(n--){
cin>>x;
ans^=x;
}
cout<<ans<<'\n';
}