美文网首页
204. Count Primes

204. Count Primes

作者: April63 | 来源:发表于2018-05-17 21:56 被阅读0次

我的方法超时了,代码如下:

class Solution(object):
    def countPrimes(self, n):
        """
        :type n: int
        :rtype: int
        """
        count = 0
        if n <= 2:
            return count
        for i in range(3, n):
            for j in range(2, i - 1):
                if i % j == 0:
                    count += 1
                    break
        return n - count - 2
                

依然超时的办法,代码如下:

class Solution(object):
    def countPrimes(self, n):
        """
        :type n: int
        :rtype: int
        """
        count = 0
        if n <= 2:
            return count
        res = []
        res.append(2)
        count = 1
        for i in range(3, n):
            j = 0 
            while j < len(res):
                if i % res[j] == 0:
                    break
                j += 1
            if j >= len(res):
                res.append(i)
                count += 1
        return count
                

传说的## 厄拉多塞筛法

class Solution(object):
    def countPrimes(self, n):
        """
        :type n: int
        :rtype: int
        """
        count = 0
        if n <= 2:
            return count
        res = [True for i in range(n)]
        res[0] = False
        res[1] = False
        for i in range(2, int(n**0.5)+1):
            if res[i]:
                res[i*i:n:i] = [False] * len(res[i*i:n:i])
        return sum(res)
                
                

相关文章

  • 204.Count Primes

    204. Count Primes Count the number of prime numbers less ...

  • 2019-01-21

    LeetCode 204. Count Primes Description Count the number o...

  • 204. Count Primes

    我的方法超时了,代码如下: 依然超时的办法,代码如下: 传说的## 厄拉多塞筛法

  • 204. Count Primes

    Description: Count the number of prime numbers less than ...

  • 204. Count Primes

    1.描述 Description: Count the number of prime numbers less ...

  • 204. Count Primes

    n以内素数的个数。 参考:埃拉托斯特尼筛法和素数判断 代码:

  • 204. Count Primes

    统计所有小于非负整数n 的质数的数量。 思路:x是质数,那么大于x的x的倍数 2x,3x一定不是质数,假如 isP...

  • Count Primes 2018-05-01

    204. Count Primes Prime number 2 3 5 7以及-上述四个数字的倍数外的其他数字(...

  • [Leetcode] 204. Count Primes

    Count Primes Description:Count the number of prime number...

  • Leetcode 204. Count Primes

    Description:Count the number of prime numbers less than a...

网友评论

      本文标题:204. Count Primes

      本文链接:https://www.haomeiwen.com/subject/iawidftx.html