LeetCode 204. 计数质数

原题目:https://leetcode-cn.com/problems/count-primes/

 

代码1;

class Solution {

private:
    bool find(int a){
        for(int i=2;i*i<=a;i++){
            if(a%i==0) return false;
        }
        return true;
    }
public:
    int countPrimes(int n) {
        int count = 0;
        for(int i=2;i

 

代码2:

class Solution {
public:
int countPrimes(int n) {
    vector isPrim(n,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;
}
};

 

 

你可能感兴趣的:(LeetCode)