Count Primes Leetcode #204 题解[Python]

题目来源


https://leetcode.com/problems/count-primes/description/

题目描述


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

Example:

Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.

给出一个数,求出小于它的有多少个素数.

解题思路


实不相瞒, 看到这道题我的第一反应是打个超级大的素数表. 强行忍住冲动写了个暴力枚举遍历的方法, 结果交上去之后发现虽然AC了, 但时间1288ms排在倒数15%.

然后看了看讨论区, 发现有大神用一大堆费马大小定理, 埃拉托色尼筛等数学定理, 居然有把时间压缩到100ms以内的, 但这些方法太难讲清楚, 逻辑也相当复杂, 这里只搬运一种比较简单的方法.

我们都知道, 一个合数必然能分解成质因子之积. 因此我们每当找到一个素数, 设它为 i, 那么对于 2 i , 3 i , 4 i , . . . . , n 这些数来说肯定都是合数. 照着这个思想, 再吃几颗Python的语法糖, 我们便能把速度拉上去.

代码实现


class Solution:
# @param {integer} n
# @return {integer}
    def countPrimes(self, n):
        if n < 3:
            return 0
        primes = [True] * n
        primes[0] = primes[1] = False
        for i in range(2, int(n ** 0.5) + 1):
            if primes[i]:
                primes[i * i: n: i] = [False] * len(primes[i * i: n: i])
        return sum(primes)

代码表现


204_ac

猜你喜欢

转载自blog.csdn.net/wayne_mai/article/details/80291300