Number Theory - prime number sieve method

First, Eratosthenes (Eratosthenes) sieve

Algorithm idea:

  To get all the prime numbers within a natural number n, must be no greater than  all multiples of primes removed, the rest is prime. Sieve to give numerical range n, find within primes . 2 to mesh with the first, i.e., the two left, weed out the multiples of 2; then the next prime number , i.e. 3 sieve, leaving the 3, weed out the multiples of 3; next with the next prime number 5 sieve , leaving the 5, the 5 multiple weed out; repeat go .......

Template title link: sieve prime number

Code implementation: The time complexity of O (nloglogn)

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <cstring>
 4 #include <cstdio>
 5 const int N = 10000000+10;
 6 int p[N];
 7 
 8 void prime(int n)
 9 {
10     p[1]=1;
11     for(int i=2;i<=n;i++)
12     {
13         if(p[i])continue;
14         for(int j=2;j<=n/i;j++)p[i*j]=1;
15     }
16 }
17 
18 int main()
19 {
20     int n;scanf("%d",&n);
21     prime(n);
22     int ans=0;
23     for(int i=1;i<=n;i++)
24         if(!p[i])ans++;
25     printf("%d\n",years);
26      return  0 ;
27 }

Two Euler (the Euler) sieve

  Euler sieve sieve make up Eppendorf repeat sieve Dealloyed number of defects, and ensures that each number will be engaged and will be screened to the screen to a minimum quality factor , while the screen is also a prime number each come to the minimum number of prime factors, serve two purposes, is a very commonly used algorithm of number theory is also very important.

  First code on: time complexity of O (n)

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <cstring>
 4 #include <cstdio>
 5 const int N = 10000000+10;
 6 
 7 int primes[N],cnt;
 8 int vis[N];
 9 
10 void Euler_prime(int n)
11 {
12     for(int i=2;i<=n;i++)
13     {
14         if(!vis[i])primes[++cnt]=i;
15         for(int j=1;primes[j]<=n/i;j++)
16         {
17             vis[primes[j]*i]=1;
18             if(i%primes[j]==0)break;
19         }
20     }
21 }
22 
23 int main()
24 {
25     int n;scanf("%d",&n);
26     Euler_prime(n);
27 
28     printf("%d\n",cnt);
29     return 0;
30 }

  Algorithms understand:

  18, the row of code ensures primes [j] equal to all prime factors must be smaller than the i (out of the cycle will be enumerated as if primes [j] to enumerate a prime factors of i), it primes [j] is primes [j] * i minimum quality factor.

  The following proof: all data will be combined with a minimum quality factor to screen, and will be screened again.

  For any one composite number k, it can be expressed as k = p * (k / p), p k is smallest prime factors. Since all prime factors p ≤ (k / p) a (k / p of code equivalent to the above-described i), it is only when the enumerator i to k / p k will be screened to time, and to enumerate any other the number of screens are not going k.

 

Guess you like

Origin www.cnblogs.com/ninedream/p/11210339.html