-1

I'm trying to make a simple sieve with vectors :

#include<iostream>
#include<vector>
#include<cmath>
using namespace std;

vector<int> myVector;

void vec_sieve()
{
    myVector.push_back(0);
    myVector.push_back(0);

    unsigned int sz = pow(2,31);
    for(unsigned int i=2;i<sz;i++)
    {
        myVector.push_back(1);
    }

    int len = sqrt(sz);
    for(unsigned int i=2;i<=len;i++)
    {
        if(myVector[i] == 1)
        {
            for(unsigned int j=2;i*j<=sz;j++)
            {
                myVector[i*j] = 0;
            }
        }
    }
}

int main()
{   
    vec_sieve();
    int n;
    cin>>n;
    unsigned int input;

    for(int i=0;i<n;i++)
    {
        cin>>input;
        if(myVector[input] == 1)
        {
            cout<<"Prime"<<endl;
        }
        else
        {
            cout<<"Not Prime"<<endl;
        }
    }

    return 0;
}

I'm new to vector and trying to create vectors of primes with seive, but somehow I am getting Bad_Alloc
Anyone could be specific about this bad allocation?
Thanks in advance

Phil Anderson
  • 3,146
  • 13
  • 24
inhaler
  • 175
  • 1
  • 2
  • 12

1 Answers1

1

std::bad_alloc is probably thrown because you are trying to allocate a contiguous memory block in the virtual memory which is too large to fit in any of its "gaps".

unsigned int sz = pow(2,31); // too large

2^31 multiplied by 4 bytes (size of int) is 8 gb. You should always first think about "how much memory does it allocate" when it comes to sizing arrays. In addition, bool is sufficient for containing 1's and 0's. vector<bool> optimizes the memory even more.

Some other observations related to your code:

Instead of this:

for(unsigned int i=2;i<sz;i++)
{
    myVector.push_back(1);
}

Use this:

myVector.resize (sz, 1);
cat
  • 36
  • 1
  • 6
  • But,my input limit will be upto 10^31.So,can u tell me how i'm going to use sieve with this long type of input. Thank u – inhaler Jun 16 '16 at 12:17
  • I can't imagine why would one need to work with such big values. Even the precalculation lasts for many seconds. – cat Jun 16 '16 at 15:53