Prime number sieve method (template)

Primes: integer greater than 1, and if only contains a number of two to about itself, it is a prime number

Trial division:

 The time complexity of O (sqrt (n))

Code:

static  Boolean Prime ( int n-) {
         IF (n-<2) return  to false ;
         for ( int i = 2; i <= n / i; i ++ ) {// Since i is divisible, the n / i certainly be divisible by n
             IF (n% I == 0) return  to false ;
        }
        return true;
    }

Linear Euler screen:

Composite number will only be its smallest prime factors screened out

Time complexity: O (n)

        static final int N=;
        static int prime[]=new int[N];
        static boolean vis[]=new boolean[N];
        static int cnt=0;
        static void get_primes(int n){
            for(int i=2;i<=n;i++){
                    if(!vis[i]) prime[cnt++]=i;
                    for(int j=0;j<cnt && prime[j]*i<=n;j++){
                            VIS [i * prime [j]] = to true ;
                             IF (i% prime [j] == 0) BREAK ; // prime [j] is the smallest prime factors of i, then the prime [j] certainly i * prime [ j] is the smallest prime factors
                    }
            }
        }

 

Egyptian style sieve method:

Time complexity: O (n * loglogn) at N = 10 ^ 6, and the time sieve Euler almost linear, but the linear Euler 10 ^ 7 sieve to twice as fast

A number is prime, then it's certainly not a multiple of prime number

Code:

        static final int N=;
        static int prime[]=new int[N];
        static boolean vis[]=new boolean[N];
        static int cnt=0;
        static void get_primes(int n){
                for(int i=2;i<=n;i++){
                        if(!vis[i]){
                                vis[i]=true;
                                prime[cnt++]=i;
                                for(int j=i+i;j<=n;j+=i)
                                     vis[j]=true;
                        }
                }
        }                    

 

Guess you like

Origin www.cnblogs.com/qdu-lkc/p/12259173.html