首页 > 学院 > 开发设计 > 正文

LeetCode 204. Count Primes

2019-11-14 13:04:47
字体:
来源:转载
供稿:网友

解题思路:维基百科中 https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes 

 Input: an integer n > 1.  Let A be an array of Boolean values, indexed by integers 2 to n, initially all set to true.  for i = 2, 3, 4, ..., not exceeding √n:   if A[i] is true:     for j = i2, i2+i, i2+2i, i2+3i, ..., not exceeding n:       A[j] := false.  Output: all i such that A[i] is true.

class Solution {public:        int countPRimes(int n) {            if (2 >= n) return 0;            vector<bool>primes(n,true);            int sqr = sqrt(n - 1);            for (int i = 2; i <= sqr; ++i){                if (primes[i]){                    for (int j = i * i; j < n; j += i)                    primes[j] = false;            }            }            int sum = 0;            for (int i = 2; i < n; ++i)                sum += (primes[i]) ? 1 : 0;            return sum;    }};


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表