Dust Mr. Law
Time complexity is \ (O (nloglogn) \) , without the complexity of a small sieve Euler
code is as follows:
void prime()
{
num[0] = num[1] = 1;//特判
for (int i = 2; i < MAX; i++)
{
if (num[i])
continue;
for (int j = i * 2; j < MAX; j += i)//质数的倍数肯定不是素数
num[j] = 1;
}
}
Euler's sieve method
Time complexity is \ (O (n) \) linear order, it is also called Euler sieve linear sieve
void Prime()//0为质数,1为非质数
{
for(int i=2;i<n;i++)
{
if(!visit[i])
{
prime[++prime[0]]=i;//将素数存储下来
}
for(int j=1;j<=prime[0]&&i*prime[j]<MAXN;j++)
{
visit[i*prime[j]]=1;//不是像埃氏法一样用i的倍数消去和数,而是通过所有记录的素数,当作要消去数的最小素因子来消去
if(i%prime[j]==0)//解释看下面
{
break;
}
}
}
}
if(i%prime[j]==0)
{
break;
}
If there is no break, when \ (I \) is \ (prime [j] \) at a multiple \ (I = K * Prime [J] \) , when (j = j + 1 \) \ When the \ (i * Prime [J +. 1] = K * Prime [J] * Prime [J +. 1] \) , since the Euler method is a screening a minimum quality factor to screen, so \ (prime [j] * prime [j + 1] \) double counting later.
For example, when \ (I =. 8, J =. 1, Prime [J] = 2 \) , when (j = j + 1 \) \ When the \ (i * prime [j + 1] = 8 * 3 = 2 * 4 3 * 2 * 12 = \) , but in the \ (I = 12 \) calculates the time, so the calculation is repeated.