leetcode-204-Count Primes

来源:互联网 发布:二维数组排序 php 编辑:程序博客网 时间:2024/05/30 02:52

                                                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;    }};


1 0
原创粉丝点击