Python force button brushing record-204. Counting prime numbers

topic:

Count the number of all prime numbers less than a non-negative integer n.
Insert picture description here

Method 1:
Violence

class Solution:
    def countPrimes(self, n: int) -> int:
        count = 0
        if n > 1:
            for i in range(2, n):
                flag = True
                for j in range(2, i):
                    if i % j == 0:
                        flag = False
                        break
                if flag:
                    count += 1
        return count

The method is simple, but the time has expired and the test cannot be passed

Method two: the
Eradosé sieve method, the method shared by the great gods on the force button:
for example, find the number of prime numbers within 20. First, 0 and 1 are not prime numbers. 2 is the first prime number, and then all 2 within 20 Cross out the multiples of 2. The number immediately following 2 is the next prime number 3, and then all multiples of 3 are crossed out. The number immediately following 3 is the next prime number 5, and then all multiples of 5 are crossed out. And so on.
Insert picture description here

class Solution: 
    def countPrimes(self, n: int) -> int:
        if n < 3:
            return 0
        else:
            output = [1] * n  # 产生一个元素全部为1的列表
            output[0], output[1] = 0, 0  # 0,1不是质数,直接赋值为0
            for i in range(2, int(n**0.5)+1):  # 从2开始,output[2]==1表示第一个质数是2,然后将2的倍数对应的索引全部赋值为0,此时下一个数output[3]==1,也是表示质数,同样划去3的倍数,以此类推
                if output[i] == 1:
                    output[i*i:n:i] = [0] * len(output[i*i:n:i])
            #最后output中的数字表示该位置上的数为质数,然后求和即可
        return sum(output)

Guess you like

Origin blog.csdn.net/weixin_45455015/article/details/110605356