码迷,mamicode.com
首页 > 其他好文 > 详细

204. Count Primes

时间:2020-04-06 00:11:19      阅读:84      评论:0      收藏:0      [点我收藏+]

标签:out   strong   NPU   example   ++   less   HERE   vector   xpl   

Problem:

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

Example:

Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.

思路

Solution (C++):

int countPrimes(int n) {
    int count = 0;
    vector<bool> isPrime(n, false);
    for (int i = 2; i < n; ++i) {
        isPrime[i] = true;
    }
    for (int i = 2; i*i < n; ++i) {
        if (!isPrime[i])  continue;
        for (int j = i * i; j < n; j += i) {
            isPrime[j] = false;
        }
    }
    for (int i = 2; i < n; ++i) {
        if (isPrime[i])  ++count;
    }
    return count;
}

性能

Runtime: 208 ms??Memory Usage: 6.6 MB

思路

Solution (C++):


性能

Runtime: ms??Memory Usage: MB

204. Count Primes

标签:out   strong   NPU   example   ++   less   HERE   vector   xpl   

原文地址:https://www.cnblogs.com/dysjtu1995/p/12639867.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!