Java LeetCode 204. Counting prime numbers

Count the number of all prime numbers less than a non-negative integer n.
Example 1:
Input: n = 10
Output: 4
Explanation: There are 4 prime numbers less than 10, and they are 2, 3, 5, 7.
Example 2:
Input: n = 0
Output: 0
Example 3:
Input: n = 1
Output: 0

Prime number (Prime number), also known as prime number, refers to the number of natural numbers greater than 1, except 1 and the number itself, that cannot be divisible by other natural numbers. ---Wikipedia

The filtering method is used here, starting from 2 and traversing to sqrt(n), because the subsequent operations are repeated

If the position of the element i is true, (false means it has been deleted, not a prime number), it means that the element i at the position is a prime number, and each deletion starts from i 2 (because the number before i 2 has been deleted ), delete every i positions

Finally, count the number of true
Insert picture description here

class Solution {
    
    
    public int countPrimes(int n) {
    
    
        if(n<2){
    
    
            return 0;
        }
        int sum=0;
        boolean[] b = new boolean[n];
        Arrays.fill(b,true);
        for(int i=2;i*i<n;i++){
    
    
            if(b[i]){
    
    
                for(int j=i*i;j<n;j+=i){
    
    
                    b[j]=false;
                }
            }
        }

        for(int i=2;i<n;i++){
    
    
            if(b[i]){
    
    
                sum++;
            }
        }
        return sum;
    }
}

Guess you like

Origin blog.csdn.net/sakura_wmh/article/details/110542482