• leetcode-easy-math-204 Count Primes-NO


    mycode     time limited

    class Solution(object):
        def countPrimes(self, n):
            """
            :type n: int
            :rtype: int
            """
            if n < 3: return 0
          
            def is_primes(x):
                for i in range(2,x):
                    if x % i == 0:
                        return False
                return True
            
            count = 0
        
            for i in range(2,n):
                if is_primes(i) :
                    print(i)
                    count += 1 
            return count
                

    参考 

    1  

    class Solution(object):
        def countPrimes(self, n):
            """
            :type n: int
            :rtype: int
            """
            if n <= 2:
                return 0
            
            prime = [1] * n
            prime[0] = prime[1] = 0
            
            for index in range(2, n):
                if prime[index] == 1:
                    time = 2
                    while index * time < n:
                        prime[index * time] = 0
                        time += 1
                        
            return sum(prime)    

    2

    class Solution:
        def countPrimes(self, n: int) -> int:
            if n < 2: return 0
            
            prime = [1]*n
            
            for i in range(2,int(n*0.5)+1):
                prime[i*i:n:i] = [0] * len(prime[i*i:n:i])
            
            return sum(prime)-2 #-2 because 0 and 1 is not a prime number

    更快优化

    import math
    
    class Solution(object):
        def countPrimes(self, n):
            """
            :type n: int
            :rtype: int
            """
            
            if n < 2:
                return 0
            s = [1] * n
            s[0] = s[1] = 0
            for i in range(2, int(n ** 0.5) + 1):
                if s[i] == 1:
                    s[i*i:n:i] = [0] * int((n-i*i-1)/i + 1)               
            return sum(s)

    time limited

    class Solution(object):
        def countPrimes(self, n):
            """
            :type n: int
            :rtype: int
            """
            count = 0
            for i in range(2,n):
                count += self.isPrime(i)     
            return count
    
        def isPrime(self,x):
            x_= int(x**0.5+1)
            for i in range(2,x_):
                if x % i == 0:
                    return 0
            return 1
  • 相关阅读:
    Java_zip_多源文件压缩到指定目录下
    Linux:ps -ef命令
    Linux:find命令中
    String.split()与StringUtils.split()的区别
    StringUtils工具类的常用方法
    Java:substring()
    Java:indexof()
    Linux:grep命令
    12、spring工厂+web前台搭建
    11、redis使用ruby实现集群高可用
  • 原文地址:https://www.cnblogs.com/rosyYY/p/11003960.html
Copyright © 2020-2023  润新知