#include <iostream> #define N 1<<20 #define M 1<<17 typedef unsigned char uchar; using namespace std; uchar isPrime[M]; uchar masks[8] = {1, 1 << 1, 1 << 2, 1 << 3, 1 << 4, 1 << 5, 1 << 6, 1 << 7};
#include <iostream> #define N 1<<20 #define M 1<<17 typedef unsigned char uchar; using namespace std; uchar isPrime[M]; uchar masks[8] = {1, 1 << 1, 1 << 2, 1 << 3, 1 << 4, 1 << 5, 1 << 6, 1 << 7}; void init(int n) { int i; for (i = 0; i <= n; i++) { isPrime[i] = 255; } } void FindPrimesTo(int n) { int group, order; group = 0; isPrime[group] ^= 1 << 7; isPrime[group] ^= 1 << 6; int index1, index2; for (index1 = 2; index1 <= n; index1++) { group = index1 / 8; order = 7 - (index1 % 8); if ((isPrime[group]&(1 << order)) > 0) { for (index2 = index1 * 2; index2 <= n; index2 += index1) { group = index2 / 8; order = index2 % 8; isPrime[group] = (isPrime[group] & masks[7 - order]) ? (isPrime[group]^masks[7 - order]) : isPrime[group]; } } } } int main(int argc, char** argv) { init((M) - 1); FindPrimesTo((N) - 1); cout << " PRIME TEST APPLICATION" << endl; cout << " ----------------------" << endl; cout << " Enter 0 to exit!" << endl << endl; int option = 1, nr; while (option != 0) { nr = -1; while ((nr < 0) || (nr > 1000000)) { cout << " nr = "; cin >> nr; } option = nr; cout << " "; int group = nr / 8; int order = nr % 8; if (isPrime[group] & masks[7 - order]) { cout << nr << " is a prime number!"; } else { cout << nr << " is not a prime number!"; } cout << endl; } cout << " Done! Now exiting ..." << endl; return 0; }