Linear sieve
Because the complexity of linear complexity, so called linear sieve method
, although I do not see where is linear, but is linear and true.
Cai ┭┮﹏┭┮ own good daily lamented
Prime [i] of the i-th storage array prime
QWE [i] i stored minimum quality factor
as a product of the number n can be regarded as the minimum quality factor q of i and the maximum factor
i.e. n = p · q
so it can help determine the next i value and then increase q back screen!
I = 15 for example can be screened out 15 × 2 = 30 15 × 3 = 45
Of course, some small detail to note is the very
first time it is to ensure that the minimum quality q is n factor is not really guaranteed may be, but it is not linear sieve method, and will greatly increase the complexity of drop
followed it to note that q * i can not> maxn resulting array bounds!
const int maxn=6666;
int prime[maxn];
int qwe[maxn];
void qprimes()
{
memset (prime,0,sizeof(prime));
memset (qwe,0,sizeof(qwe));
int tmp=0;
for (int i=2;i<=maxn;i++)
{
if (qwe[i]==0)
qwe[i]=prime[++tmp]=i;
for (int j=1;j<=tmp;j++)
{
if (prime[j]*i>maxn||prime[j]>qwe[i])
break;
qwe[i*prime[j]]=prime[j];
}
}
}