Question 47-Calculate the number of prime numbers within n

To calculate the number of prime numbers within n (not including n) in a relatively efficient way

Solution 1 Exhaustive

int countPrimes(int n) {
    
    
    int count = 0;
    for (int i = 2; i < n; i++)
        if (isPrim(i)) count++;
    return count;
}

// 判断整数 n 是否是素数
boolean isPrime(int n) {
    
    
    for (int i = 2; i * i < n; i++)
        if (n % i == 0)
            // 有其他整除因子
            return false;
    return true;
}

Solution 2 Sieve of Eratosthenes

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

Guess you like

Origin blog.csdn.net/Awt_FuDongLai/article/details/112349592