[Leetcode] #204 Count Primes

来源:互联网 发布:java gettime 函数 编辑:程序博客网 时间:2024/05/17 01:15

Discription:

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

Solution:

int  countPrimes(int n){ //埃拉托斯特尼筛法  2到n所有素数vector<bool> nums(n, true);for (int i = 2; i < sqrt(n); i++){if (!nums[i]) continue;int j = i*i;while (j < n){nums[j] = false;j += i;}}int result = 0;for (int i = 2; i < n; i++){if (nums[i])result++;}return result;}

0 0
原创粉丝点击