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

leetcode-204-Count Primes

时间:2015-07-26 21:01:15      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:leetcode

                                                Count Primes

Description:

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


题目 Count Primes



计算小于n的所有素数的总数。

用一般的方法超时,应该用筛选法求素数 ,参考 筛选法求素数

class Solution {
public:
       
    int countPrimes(int n) {
        int* a = new int[n]();
        int ans = 0;
        int m = sqrt(n);
        for (int i = 2;i <= m;i++) {
            if (!a[i]) {
                for (int j = i * i;j < n;j = j + i) a[j] = 1;// 标记因子为i的合数
            }
        }
        
        for (int i = 2;i < n;i++){
            if (!a[i]) ans++;
        }
        
        return ans;
    }
};


版权声明:本文为博主原创文章,未经博主允许不得转载。

leetcode-204-Count Primes

标签:leetcode

原文地址:http://blog.csdn.net/u014705854/article/details/47070717

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