Eratosthenes screening for prime numbers

Explanation: In addition to itself, a number that cannot be divisible by other integers is called a prime number. It is very simple to require a prime number, but how to quickly find a prime number has always been a problem for programmers and mathematicians. The well-known Eratosthenes method for finding prime numbers.


Solution: First of all, know that this problem can be solved by using a loop. Divide a specified number by all numbers smaller than it. If it can be divisible, it is not a prime number. However, how to reduce the number of loop checks? How to find all prime numbers less than N? First, suppose that the number to be checked is N, then in fact, you only need to check to the root of N. The reason is very simple. Assuming that A*B = N, if A is greater than the root of N, then in fact If the check before A is smaller than A, you can first check that the number B is divisible by N. However, using the root number in the program will cause accuracy problems, so you can use i*i <= N to check, and the execution is faster. Suppose there is a sieve to store 1~N, for example:

2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 ........ N

First sieve out the multiples of 2:

2 3 5 7 9 11 13 15 17 19 21 ........ N

Then sieve out the multiples of 3:

2 3 5 7 11 13 17 19 ........ N

Then sieve out the multiples of 5, then sieve out the prime numbers of 7, and then sieve out the multiples of 11......, so the numbers left at the end are all prime numbers, this is the Eratosthenes screening method (Eratosthenes Sieve Method). The number of checks can be further reduced. In fact, you only need to check 6n+1 and 6n+5, that is, skip the multiples of 2 and 3 directly, so that the checking actions of if in the program can be reduced.

#include <stdio.h>
#include <stdlib.h>
#define N 1000
int main(void) {
    int i, j;
    int prime[N+1];
    for(i = 2; i <= N; i++)
        prime[i] = 1;
    for(i = 2; i*i <= N; i++) { // 这边可以改进
        if(prime[i] == 1) {
            for(j = 2*i; j <= N; j++) {
                if(j % i == 0)
                    prime[j] = 0;
            }
        }
    }
    for(i = 2; i < N; i++) {
        if(prime[i] == 1) {
            printf("%4d ", i);
            if(i % 16 == 0)
                printf("\n");
        }
    }
    printf("\n");
    return 0;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324497061&siteId=291194637