Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 356
  • Last Modified:

Prime Number Table - Constant Seach Time

After a question with sunnycoder about searchtimes of sorted arrays, I've decided to try something out.

I want to be able to determine if a number is prime, a number between (1-10,000,000) in a constant period of time.

How I plan to do this is I'm going to make a list of prime numbers between 1-10,000,000 in an array.

So it would make sense to use an array with 10,000,000 boolean elements, but this is really overkill, since all i need is a single bit and not an 8bit boolean.

So what I was thinking was making an array of 10,000,000/32  elements, because each bit of the 32bit number can represent the boolean value for the number being prime. So for example, say I wanted to determine if the number 17 was prime, I would only need a single 32bit number, where the each bit was set corresponding to the number being prime or not so it would be something like: 0010101000101001010001000001010, does this make sense?
                                                                                                                     3  5  7    11 13 17 19  23       29  31

So since I know which bit in the number corresponds to 17 being prime or not, its rather trivial to determine whether or not 17 is prime.

The reason i'm doing it this way is just because I want to minimize the size of the array. Where with 8bit values i would have 10,000,000 bytes, by doing it like this the array size would become something like 10,000,000 / 8bits or around 1,250,000 bytes around (1mb vs 10mb).

Make sense?

I'm not really sure how to go about something like this. Figuring out if a number is prime seems pretty simple...

  value = primeTable[(Number / 32)]
  bitPosition =  (Number % 32)
  bitValue = ((Number << bitPosition) & 0x1) //right? Shift all the way to the right and bitwise and with 1???


The confusion I am having is about how to build this array, any suggestions would be appriciated.



Thanks.
Brian
     

0
BrianGEFF719
Asked:
BrianGEFF719
  • 8
  • 2
1 Solution
 
BrianGEFF719Author Commented:
Sorry my example should be:

bitValue = ((value << bitPosition) & 0x1) //right? Shift all the way to the right and bitwise and with 1???
0
 
ozoCommented:
value = primeTable[Number/8]>>number%8 & 1;
0
 
BrianGEFF719Author Commented:
>>value = primeTable[Number/8]>>number%8 & 1;
I'm using 32bit longs though, should I just use single bytes?

for example suppose I was doing it like this:

      unsigned long primeTable = 0;
      int maxPrime = sizeof(unsigned long) * 8;

      for (int i = 1; i < maxPrime; ++i)
      {
            if (isPrime(i))
            {
                  //how would I set the corresponding bit?
            }
      }
0
The IT Degree for Career Advancement

Earn your B.S. in Network Operations and Security and become a network and IT security expert. This WGU degree program curriculum was designed with tech-savvy, self-motivated students in mind – allowing you to use your technical expertise, to address real-world business problems.

 
BrianGEFF719Author Commented:
Would it be:

primeTable += i * i; ???
0
 
BrianGEFF719Author Commented:
Oh wait, I think i've got that part now:

primeTable += (1 << (i-1));
0
 
BrianGEFF719Author Commented:
This seems to work:

      unsigned long primeTable = 0;
      unsigned long temp = 0;
      int maxPrime = sizeof(unsigned long) * 8;

      for (int i = 1; i < maxPrime; ++i)
      {
            if (isPrime(i))
            {
                  primeTable += (1 << (i-1));
            }
      }

      for (i = 1; i < maxPrime; ++i)
      {
            temp = primeTable;
            if ( (temp >> (i - 1) & 1) )
            {
                  cout << i << " is prime" << endl;
            }
      }
0
 
BrianGEFF719Author Commented:
So here is the code i've come up with so far:


void main (void)
{
      long startTick,endTick,longSize=sizeof(unsigned long)*8;
      long maxPrime = 1000000;
      unsigned long *pTable;
      int numItems = (maxPrime / longSize) + 1;

      cout << numItems << " " << longSize << "bit array elements will be needed for " << maxPrime << " items " << endl;

      if ( (pTable = (unsigned long *) malloc(numItems)) == NULL)
      {
            cout << endl <<  "ERROR: Unable to allocate memory." << endl;
            exit(-1);
      }

      startTick = GetTickCount();
      cout << "Building array...";
      
      for (long i = 1; i < maxPrime; ++i)
      {
            if (isPrime(i))
            {
                  *(pTable + (i / longSize)) += (1 << ((i % 32)));
            }
      }
      
      endTick = GetTickCount();
      cout << "Done building array, Time: " << (endTick - startTick) << "ms" << endl;

      cout << endl << endl;
      system("PAUSE");
}


I'm getting an error on the line *(pTable + (i / longSize)) += (1 << ((i % 32)));, Unhandled Exception, not really sure why.


-Brian
0
 
BrianGEFF719Author Commented:
Here is my most recent version, for some reason its not  working properly and i cannot figure out why:


void main (void)
{
      long theNumber,startTick,endTick,longSize = sizeof(unsigned long) * 8,maxPrime = 1000000;
      unsigned long *pTable;
      int isItPrime,numItems = (maxPrime / longSize) + 1;

      cout << numItems << " " << longSize << "bit array elements will be needed for " << maxPrime << " items " << endl;

      if ( (pTable = new unsigned long[numItems]) == NULL)
      {
            cout << endl <<  "ERROR: Unable to allocate memory." << endl;
            exit(-1);
      }

      startTick = GetTickCount();
      cout << "Building array...";
      
      for (long i = 1; i < maxPrime; ++i)
            if (isPrime(i))
                  *(pTable + (i / longSize)) += (1 << ((i % 32)));
      
      endTick = GetTickCount();
      cout << "Done building array, Time: " << (endTick - startTick) << "ms" << endl << endl;

      do
      {
            cout << endl << "Please enter a number to check between 1 - " << maxPrime << " (0 exits): " << endl;
            cin >> theNumber;
            if (theNumber > 0 && theNumber < maxPrime)
            {
                  isItPrime = 0;
                  int val;
                  val = *(pTable + (theNumber / longSize));
                  isItPrime = (val >> (theNumber % 32) & 1);
                  cout << theNumber << ((isItPrime == 1) ? (" is prime") : (" is not prime")) << endl;
            }
      } while (theNumber > 0 && theNumber < maxPrime);


      cout << endl << endl;
      system("PAUSE");

      delete []pTable;
}
0
 
ozoCommented:
malloc(numItems) should be malloc(numItems*sizeof(*pTable))
0
 
BrianGEFF719Author Commented:
>>malloc(numItems) should be malloc(numItems*sizeof(*pTable))

Thats right malloc takes a number of bytes. I was getting it confused with the new operator in C++.
0
 
itsmeandnobodyelseCommented:
>>>> I was getting it confused with the new operator in C++.

Why didn't you use the 'new' operator?

There is no advantage using malloc over new. Especially if you are not experienced malloc is a bad choice. if using C++ class or struct, malloc/free doesn't invoke constructor/destructor what will cause the next headache.

>>>> where the each bit was set corresponding to the number being prime
>>>> Make sense?

Using template class bitset would turn the prog to

#include <bitset>
#include <iostream>
using namespace std;

int main ()
{
     long theNumber,startTick,endTick;
     const size_t maxPrime = 1000000;
     bool isItPrime;
     bitset<maxPrime> primeBits;

     cout << "Building bitset...";
     startTick = GetTickCount();
     
     long l;
     primeBits.reset();

     for (l = 0 ; l < maxPrime; ++l )
     {
         if (isPrime(++l))
         {
            primeBits.set(l, true);
         }
     }
     
     endTick = GetTickCount();
     cout << "Done building array, Time: " << (endTick - startTick) << "ms" << endl << endl;

     do
     {
          cout << endl << "Please enter a number to check between 1 - " << maxPrime << " (0 exits): " << endl;
          cin >> theNumber;
          if (theNumber > 2 && theNumber < maxPrime)
          {
               isItPrime = primeBits[theNumber];

               cout << theNumber << ((isItPrime) ? (" is prime") : (" is not prime")) << endl;
          }
     } while (theNumber > 0 && theNumber < maxPrime);

     cout << endl << endl;
     system("PAUSE");

     return 0;
}




Regards, Alex



0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Building an Effective Phishing Protection Program

Join Director of Product Management Todd OBoyle on April 26th as he covers the key elements of a phishing protection program. Whether you’re an old hat at phishing education or considering starting a program -- we'll discuss critical components that should be in any program.

  • 8
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now