首页 > 其他 > 详细

LeetCode204——count primes

时间:2016-01-20 19:17:42      阅读:235      评论:0      收藏:0      [点我收藏+]

方法还是有很多的,通过率很低,不过这题还是需要思考清楚,不然很容易t

class Solution {
public:
    int countPrimes(int n)
    {
        if(n == 0 || n == 1)
        {
            return 0;
        }
        int cnt = 0;
        bool* isPrime = new bool[n];
        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])
            {
                cnt ++;
            }
        }
        delete[] isPrime;
        isPrime = NULL;
        return cnt;
    }
};

 

LeetCode204——count primes

原文:http://www.cnblogs.com/thewaytomakemiracle/p/5146093.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!