Quick Prime Number Test - Method: Advanced
Submitted by DoctorSpeedCode on Saturday, August 9, 2014 - 18:12.
While the last Quick Prime Number Test was done at a basic level, today we are going to advance and used much more from what can be done in C++.
The declarations will now be the following:
Let us clarify what these are for! The bitwise shifting operator () is used to shift bits to the left. X N would mean that the number X, in binary representation, will be shifted left with N positions.
For example, let's look at the following:
This will output 128! This happens because from the right side, a 0 bit enters, and to the left, since int is 4 bytes or 32 bits on most platforms, it will simply move left and eliminate the leftmost bit. The elimination would happen in any case, regardless of the bit's value (0 or 1).
So, a way to calculate 2^N is 1main.cpp source code. We have re-written the one from the last prime test tutorial, to work with the masks and the new form of representation.
Now, you can tell anyone you know advanced C++ and even test primes like this! Enjoy!
- #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};
- int x = 64;
- x <<= 1;
- cout << x << endl;
- #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;
- }
Add new comment
- 22 views