Title: Given an n, find all prime numbers of 1~n.
Here are two methods for selecting prime numbers:
The first type: ordinary Sieve method.
Time complexity is O (Nloglogn), and the disadvantage is that a composite number may be filtered multiple times.
Code:
void Prime ()
{
memset (tag,0,sizeof (tag));
Tag[0]=tag[1]=1;
for (int i=2; i*i <= N; i++)
if (tag[i]==0) {
prime[ct++]=i;
for (int j=i+i;j<=n;j+=i)
tag[j]=1
}
}
The second type: linear sieve.
The time complexity is O (n), because each composite is guaranteed to be filtered only by its smallest mass factor. The key code in the 10th, 11 lines, because if I can complete out of prime[j], then I must be a composite, and I have the quality factor is certainly less than prime[j], so this can stop, because the back of the prime[] than I small of that quality factor to be larger.
Code:
void Prime () {
memset (tag,0,sizeof (tag));
int cnt=0;
Tag[0]=tag[1]=1;
for (int i = 2; i<n; i++) {
if (!tag[i])
prime[cnt++]=i;
for (int j=0;j<cnt && prime[j]*i<n; j + +) {
Tag[i*prime[j]] = 1;
if (i% prime[j]==0) break;}}