Last active
January 27, 2023 16:46
-
-
Save uxdxdev/5d55bc8f6dfb5d0bc522ba4444eed4a0 to your computer and use it in GitHub Desktop.
EPI C++ 5.1 Computing the parity of a word
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> | |
#include <sstream> | |
#include <map> | |
using namespace std; | |
std::map<unsigned int, short> parityCache; | |
short parityOf(unsigned long x){ | |
short result = 0; | |
while(x){ | |
result ^= (x & 1); | |
x >>= 1; | |
} | |
return result; | |
} | |
short findParityUsingParityCacheOf(unsigned long x) { | |
short result = 0; | |
const int kWordSize = 16; | |
const int kBitmask = 0xFFFF; | |
result = parityCache[x >> (3 * kWordSize)]; | |
result ^= parityCache[x >> (2 * kWordSize) & kBitmask]; | |
result ^= parityCache[(x >> kWordSize) & kBitmask]; | |
result ^= parityCache[x & kBitmask]; | |
return result; | |
} | |
void buildParityCache() { | |
std::map<unsigned int, short> cache; | |
short number = std::numeric_limits<short>::max(); | |
short result = 0; | |
while(number) { | |
result = parityOf(number); | |
cache[number] = result; | |
number--; | |
} | |
cout << "Size of parity cache " << cache.size() << endl; | |
parityCache = cache; | |
} | |
int main(int argc, char *argv[]) { | |
buildParityCache(); | |
unsigned long number = 50; | |
while(number) { | |
short result = findParityUsingParityCacheOf(number); | |
cout << "Parity of " << number << " is " << result << endl; | |
number--; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment