Skip to content

Instantly share code, notes, and snippets.

@lelandjansen
Last active September 30, 2016 19:38
Show Gist options
  • Save lelandjansen/5bb1a389271d1cc67b5aeaf783c04f99 to your computer and use it in GitHub Desktop.
Save lelandjansen/5bb1a389271d1cc67b5aeaf783c04f99 to your computer and use it in GitHub Desktop.
Compute the parity of a number (two methods)
#include <iostream>
bool PairityA(int n) {
bool res = 0;
while(n) {
res ^= n & 1;
n >>= 1;
}
return res;
}
bool PairityB(int n) {
int count = 0;
while(n) {
if (n&1) ++count;
n >>= 1;
}
return (bool)(count % 2);
}
int main() {
bool fail = false;
for (int i = 0; i < 32; ++i) {
if (PairityA(i) != PairityB(i)) {
fail = true;
std::cerr << "FAIL for " << i << std::endl;
std::cerr << "A got " << PairityA(i) << ", B got " << PairityB(i) << std::endl;
}
}
if (!fail) std::cerr << "Success!" << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment