All non-negative integer less than the number n of the number of quality statistics, Sieve of Eratosthenes

The definition of prime numbers: prime, also known prime number. Is a natural number greater than 1, except 1 and itself, the called number is not divisible by the number of other natural prime number.

1. Violence algorithm:

So that i = 2; when i <n, we iterate over primes 2-i, i.e., so that i% (2 ~ i-1), if the flag is true, i is a prime number, the counter ++; otherwise bounce , i ++; next determined once

 public int countPrimes(int n) {
    int i=2;
int count=0;
boolean flag=true;
while (i<n){
for (int j = 2; j <i ; j++) {
if(i%j==0){
flag=false;
break;
}
}
if(flag==true) {
count++;
}
flag=true;
i++;
}
return count;
}

2. Using Sieve of Eratosthenes, create a boolean array of length n, and the default value is false; we start determination directly from 2, then by 2 to the screen, i.e., the left 2, the 2 excluding multiple off; 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, weed out the multiples of 5; repeat go .... Every screened out number i * j <n, the set ture, which can reduce unnecessary computation

Time complexity: O (n * lglgn)

    public static int countPrimes(int n) {
        boolean []nums=new boolean[n];
        int count=0;
        for (int i = 2; i <n ; i++) {
            if(nums[i]==false){
                count++;
                for (int j = 2; i*j <n ; j++) {
                    nums[i*j]=true;
                }
            }
        }
        return count;
    }

 

Guess you like

Origin www.cnblogs.com/jiezai/p/11221618.html