LeetCode One Question of the Day (implemented in Python): 204. Counting prime numbers

topic

统计所有小于非负整数 n 的质数的数量。

示例 1:

输入:n = 10
输出:4
解释:小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。
示例 2:

输入:n = 0
输出:0
示例 3:

输入:n = 1
输出:0
 

提示:

0 <= n <= 5 * 106

Ideas:

Use the Erado sieve method:

求<n非负数的质数:
创建一个数组对象isPrimes = [1]*n,先开始假设每个数都为质数。
用i遍历 2~n-1:
如果isPrime[i]为1,则res+1,此时令j = i,并将所有能整除i的数设为0(必定不是素数)
详见代码:

Code:

class Solution:
    def countPrimes(self, n: int) -> int:
        isPrimes = [1] * n
        res = 0
        for i in range(2, n):
            if isPrimes[i] == 1:
                res += 1
            j = i
            while(i * j < n):
                isPrimes[i*j] = 0
                j += 1
        return res


ans = Solution()
num = int(input())
print(ans.countPrimes(num))

Guess you like

Origin blog.csdn.net/weixin_44795952/article/details/110549789