LeetCode|Count Primes

来源:互联网 发布:茉莉雨 知乎 编辑:程序博客网 时间:2024/06/08 04:20

Count Primes

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

class Solution {public:    int countPrimes(int n) {        vector<bool> isPrime(n, true);        for(int i = 4; i < n; i+=2){isPrime[i] = false;} // 0, 1 are not prime well         for(int i = 2; i <= sqrt(n); i++){            if(isPrime[i]){                for(int j = i*i; j < n; j+=(i<<1)){                    isPrime[j] = false;                }            }        }        int cnt = 0;        for(int i = 2; i < n; i++){            if(isPrime[i]){                cnt++;            }         } return cnt;    }};

筛法求素数

0 0
原创粉丝点击