204. Count Primes [easy] (Python)
来源:互联网 发布:爬虫数据采集兼职 编辑:程序博客网 时间:2024/05/16 06:00
题目链接
https://leetcode.com/problems/count-primes/
题目原文
Count the number of prime numbers less than a non-negative number, n.
题目翻译
计算小于非负数 n 的所有素数的个数。
思路方法
想要验证小于n的所有数分别是不是素数,如果暴力的判断每个数是否能整除所有小于它的数,亲测会超时,所以要采用更优的算法。
该题目给出了解决问题的提示,具体提示请到 原题目 的Hint里查看。
思路
要求小于n的所有素数,一个高效的算法是“素数筛选法”。其思想是从小的素数开始,排除该小素数的所有倍数,直到最终剩下的全是素数。具体的算法可以参考:
https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Algorithm_complexity
代码
class Solution(object): def countPrimes(self, n): """ :type n: int :rtype: int """ if n <3: return 0 digits = [1]*n digits[0] = digits[1] = 0 for i in xrange(2, int(n**0.5)+1): if digits[i] == 1: for j in xrange(i+i, n, i): digits[j] = 0 return sum(digits)
说明
注意,上面代码中的循环变量 i ,范围直到 sqrt(n)+1;循环变量 j,每次更新是 j=j+i。
上面的代码先求出所有素数,再进行计算总计多少个。一个简单的变体是在一遍遍历所有n个数的时候计算所有素数。
代码二
class Solution(object): def countPrimes(self, n): """ :type n: int :rtype: int """ if n <3: return 0 digits = [0]*n count = 1 sq = int(n**0.5)+1 for i in xrange(3, n, 2): if not digits[i]: count += 1 if i > sq: continue for j in xrange(i+i, n, i): digits[j] = 1 return count
说明
注意:相比C/C++等语言,由于Python运行效率偏低,对于该问题,有的算法用C/C++写可以AC,但用Python无法AC。
PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.csdn.net/coder_orz/article/details/51321944
0 0
- 204. Count Primes [easy] (Python)
- Easy-题目59:204. Count Primes
- Leetcode 204. Count Primes (Easy) (cpp)
- [Leetcode 204, Easy] Count Primes
- 【LeetCode】(204)Count Primes(Easy)
- 204.leetcode Count Primes (easy)[素数 数学观察]
- 【leetcode】204. Count Primes(Python & C++)
- 204. Count Primes
- 【LeetCode】204.Count Primes
- [leetcode] 204.Count Primes
- LeetCode 204. Count Primes
- Leetcode 204. Count Primes
- 204. Count Primes
- 204. Count Primes
- [LeetCode]204. Count Primes
- 204. Count Primes LeetCode
- 204. Count Primes
- 204. Count Primes
- Oracle数据库名字不能超过8位,但实例名可以超过8位
- Eclipse中出现无法找到Maven包
- Winsock网络编程客户端
- SDAU 练习三 1012 堆满骨牌问题
- 16进制数据相加,计算校验和
- 204. Count Primes [easy] (Python)
- JavaWeb中Ajax的使用-基本使用+省市联动例子
- hdu 1325判断是不是树
- [leetcode] 42. Trapping Rain Water 解题报告
- Object-c-----set方法的内存管理
- GIT常用命令
- Java集合的有序、无序、排序性质讨论
- 约瑟夫环问题(数论)
- S5P4418开发遇到的问题(持续更新)