Principle:
Number of records for the first 2~n. 2 as the smallest prime number. So more than 2 are not prime, from the recording medium crossed off, after scanning again. Use 3 as the minimum prime number. 3 times times the number of strokes off, so down, to find out all prime numbers.
As you can see in the table:
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
2 |
3 |
- |
5 |
- |
7 |
- |
9 |
- |
11 |
- |
13 |
- |
15 |
- |
17 |
- |
19 |
- |
2 |
3 |
- |
5 |
- |
7 |
- |
- |
- |
11 |
- |
13 |
- |
- |
- |
17 |
- |
19 |
- |
Code:
Infer whether it is a prime number:
BOOL Is_prime (int n) {for (int i=2;i*i<=n;i++) { if (n%i==0) return false; } return n!=1;}
Ed Sieve Method:
const int MAX = 1000;int prime[max];bool is_prime[max];int sieve (int n) { int p=0; for (int i=0;i<=n;i++) is_prime[i] = true; Is_prime[0] = is_prime[1] = false; for (int i=2;i<=n;i++) { if (Is_prime[i]) { prime[p++] = i; for (int j=2*i;j<=n;j+=i) is_prime[j] = false; } } return p;}
Soeriksen Sieve method