Last active
September 30, 2016 19:38
-
-
Save lelandjansen/5bb1a389271d1cc67b5aeaf783c04f99 to your computer and use it in GitHub Desktop.
Compute the parity of a number (two methods)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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