[LeetCode]204. Count Primes

来源:互联网 发布:淘宝直通车怎么样 编辑:程序博客网 时间:2024/05/17 00:05

Description:

Description:

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

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

————————————————————————————————————————————————————————————————————

Solution:

一开始的方法TLE了,原因是时间复杂度太高:O(n*n^1/2)

class Solution {public:    int countPrimes(int n) {        int counts = 0;        for (int i = 2; i < n; i++)            if (isPrime(i))                counts++;        return counts;    }    bool isPrime(int num) {        if (num <= 3)            return true;        for (int i = 2; i < sqrt(num) + 1; i++)            if (num % i == 0)                return false;        return true;    }};

后来使用bool数组对每个已经判断过是否为素数的数做标记,这样节省许多重复的判断步骤:


class Solution {public:    int countPrimes(int n) {        int counts = 0;        vector<bool> times(n, true);        // 1 is not prime        times[0] = false;                for (int i = 2; i < sqrt(n) + 1; i++) {            for (int j = i * i; j < n; j += i) {                times[j - 1] = false;            }        }                for (int i = 2; i < n; i++) {            if (times[i - 1])                counts++;        }                return counts;    }};


原创粉丝点击