Sieve of erathostenes

How can I write program who count prime nubers beetwen [a,b] with sieve of erathostenes but with using less memory (I use char fields)??
What do you have so far?
My program is working fine but use to much memory!

#include<cstdio>
#include<cstdlib>
#include<cmath>
using namespace std;

typedef long long int lld;

int main(void)
{
lld a,b,i,j,br=0,rj,rj2,nzd;
char *prime;

scanf("%lld %lld",&a,&b);
prime=(char *)malloc(sizeof(char)*(b+2));
for(i=0;i<=b;i++)
{
prime[i]=0;
}
prime[0]=prime[1]=1;
int granica=sqrt(b);
for(i=2;i<=granica;i++)
{
if(prime[i]==0)
{

for(j=i*i;j<=b;j+=i)
{
prime[j]=1;
}
}
}
for(i=a;i<=b;i++)
{
//printf("%d\n",prime[i]);
if(prime[i]==0)br++;
}
printf("%d\n",br);
free(prime);
//system("pause");
return 0;
}
Last edited on
Well, the sieve has a linear memory requirement. You could use an std::vector<bool>, which would take 12.5% of the memory you're using now.
I use bool fields but again it using to much memory. I pass 12/22 on one task
Your program is very hard to read (plus is in C, which I don't like very much). What helios means is that std::vector<bool> is a very special class that saves bool values in a single bit, as opposed to a complete byte, for example. But then again, this class is C++ and you seem to be using C.
Topic archived. No new replies allowed.