204. Count Primes

题目:

Description:

Count the number of prime numbers less than a non-negative number, n.

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

Show Hint 

     

    Hide Tags
      Hash Table Math  

    链接: http://leetcode.com/problems/count-primes/

    题解:

    求小于素数。正好前几天PKU的Java课上讲到埃式筛法,一下就想到了它。先建立一个数组,假定所有大于1小于n的数都mark为素数。之后从第一个素数2开始,mark这个素数的倍数为非素数。注意边界。时间复杂度等于(n/2+n/3+n/5...+n/比n小的最大素数) = n*(小于n的所有素数倒数的和) = O(n * log(logn))

    Time Complexity - O(nloglogn), Space Complexity - O(n)。                                 

    public class Solution {
    
        public int countPrimes(int n) {
    
            if(n < 2)
    
                return 0;
    
            boolean[] dp = new boolean[n];
    
            Arrays.fill(dp, 2, n, true);
    
            int result = n - 2;
    
            
    
            for(int i = 2; i * i < n; i++){
    
                if(dp[i]){                                       //if i is a prime
    
                    for(int j = i; i * j < n; j++){
    
                        if(dp[i * j]){                           //then i * j is not a prime, set dp[i * j] to false
    
                            dp[i * j] = false;
    
                            result--;
    
                        }
    
                    }
    
                }
    
            }
    
            
    
            return result;
    
        }
    
    }

    测试:

    Reference:

    http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes 

    你可能感兴趣的:(count)