I was trying to code which will generate primes. But what is wrong in my code? why it's not working !
Code:
#include<iostream.h>
#include<math.h>
void primes(long n)
{
const np = 100;
long mult[np],P[np],i,j,limit = sqrt(n),plimsq,rootn,dx,x;
bool prime;
P[1] = 2;
P[2] = 3;
P[3] = 5;
i = 3;
if(n < 5)
{
for(j=1;j<=((n+1)/2);++j)
cout << P[j];
}
else
{
for(j=1;j<=3;++j)
cout << P[j];
x = 5;
plimsq = 25;
limit = 3;
dx = 2;
rootn = sqrt(n);
while(x<n)
{
x += dx;
dx = abs(dx-6);
if(limit <= i)
{
if(x >= plimsq)
{
mult[limit] = plimsq;
limit++;
if(limit <= i)
plimsq = P[limit]*P[limit];
}
prime = true;
j = 3;
while(prime = true && j < limit)
{
while(mult[j] < x)
{
mult[j]+=P[j]*2;
prime = (x != mult[j]);
j++;
}
if(prime)
{
cout << x;
if(x <= rootn)
{
i++;
P[i] = x;
}
}
}
}
}
}
}
int main()
{
cout << " Now see the primes : " << endl;
primes(20);
cin.get();
return 0;
}
If you know better algorithms than this one let me know. If code of that algo. is included that will be really nice !!!