leetcode count prime
来源:互联网 发布:java wait 异常 编辑:程序博客网 时间:2024/06/07 17:17
https://leetcode.com/problems/count-primes/
understanding
使用sieve methods. 首先排除0和1,然后从2开始逐个做标记,令p = 2,然后从$p^2$开始scan,排除掉所有 p的倍数multiples. 然后p increase to the most recent one that not been marked. 这里直接在最外面的while循环里面加个if判断就行,不要在while里面多弄一个while
这里要注意都是从$p*p$开始,因为p*(p-1)的话,已经被p-1的p倍标记过了
mycode:
class Solution(object): def countPrimes(self, n): """ :type n: int :rtype: int """ if n == 0 or n == 1: return 0 p = 2 flag = [1]* n flag[0] = flag[1] = 0 while p*p < n: if flag[p] == 1:#直接在这里判断下一个p是什么 i = p while i * p < n: flag[i * p] = 0 i += 1 p += 1 return sum(flag)
自己重写code
class Solution(object): def countPrimes(self, n): """ :type n: int :rtype: int """ if n < 2: return 0 flag = [1]*n flag[0], flag[1] = 0, 0 p = 2 while p*p < n: if flag[p*p] == 1: i = p while p*i < n: flag[p*i] = 0 i += 1 p += 1 return sum(flag)
0 0
- Leetcode: Count Prime
- LeetCode-Count Prime
- Leetcode: Count Prime
- leetcode 204 Count Prime
- leetcode count prime
- Hoj 2276 Count prime
- [数论] HOJ 2276 Count prime 筛素数
- 解题报告 之 HOJ2276 SOJ2498 Count prime
- LeetCode: Count and Say
- [LeetCode]Count and Say
- LeetCode Count and Say
- [Leetcode] Count and Say
- Leetcode: Count and Say
- [LeetCode] Count and Say
- LeetCode Count and Say
- [LeetCode]Count and Say
- [LeetCode] Count and Say
- LeetCode-Count and Say
- 集合排序aA-zZ
- WindowManager.LayoutParams:(二:softInputMode)
- Objective-C中,重写init方法为什么要self = [super init]
- Ehcache对并发的支持
- 棋盘覆盖问题
- leetcode count prime
- 网络编程--URL,URLConnection
- Js获取当前日期时间及其它操作
- android应用启动流程
- 开放有限元分析计算平台介绍
- C++双冒号(::)的用法
- [转载]一篇非常好的博文,C语言提防unsigned
- 图片裁剪问题
- android:windowsoftinputmode=“adjustresize” 无效的解决办法