[leetcode] 204. Count Primes 解题报告

题目链接:https://leetcode.com/problems/count-primes/

Description:

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


思路:筛选法求素数

代码如下:

class Solution {
public:
bool flag[2000000];
int countPrimes(int n) {
    for(int i =0; i<= n; i++) 
        flag[i] = true; 
    for(int i = 2; i*i <= n; i++) 
    { 
        for(int j = 2*i; j< n; j+= i ) 
        { 
            flag[j] = false; 
        } 
    } 
    int cnt = 0; 
    for(int i = 2; i< n; i++) 
        if(true == flag[i]) 
            cnt++; 
    return cnt; 
} 

};


你可能感兴趣的:(LeetCode,素数)