【LEETCODE】204-Count Primes
来源:互联网 发布:lrc歌词编辑软件 编辑:程序博客网 时间:2024/06/08 10:59
Description:
Count the number of prime numbers less than a non-negative number,n.
思路:
The Sieve of Eratosthenes is one of the most efficient ways to find all prime numbers up ton.
埃拉托斯特尼筛法 (http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes)
1. Create a list of consecutive integers from 2 through n: (2, 3, 4, ..., n).
2. Initially, let p equal 2, the smallest prime number.
3. Starting from p, enumerate its multiples by counting to n in increments of p, and mark them in the list (these will be 2p, 3p, 4p, ... ; the p itself should not be marked).
4. Find the first number greater than p in the list that is not marked. If there was no such number, stop. Otherwise, let p now equal this new number (which is the next prime), and repeat from step 3.
class Solution(object): def countPrimes(self, n): """ :type n: int :rtype: int """ isprime=[True]*max(n,2) #1~n先全部设定为true isprime[0]=isprime[1]=False #1和2初始化为false i=2 while i*i<n: #因n=i*j,且i<=j,则 i*i<span style="font-family: Arial, Helvetica, sans-serif;"><n</span> if isprime[i]: #只需要check还不是false的i p=i*i #比i小的部分i*1~i*(i-1)已经被check过了,所以直接判断i*i的 while p<n: isprime[p]=False p+=i #p+i i+=1 return sum(isprime)
- LeetCode 204 - Count Primes
- LeetCode 204-Count Primes
- [LeetCode 204] Count Primes
- leetcode 204: Count Primes
- LeetCode 204:Count Primes
- leetcode-204 Count Primes
- Count Primes - LeetCode 204
- Leetcode 204 Count Primes
- leetcode[204]:Count Primes
- Leetcode 204 Count Primes
- leetcode-204 Count Primes
- leetcode 204:Count Primes
- leetcode-204-Count Primes
- leetCode #204 Count Primes
- leetcode 204: Count Primes
- LeetCode 204 Count Primes
- [leetcode 204] Count Primes
- 【LEETCODE】204-Count Primes
- 排序算法:堆排序
- 面试题12:二进制中1的个数
- woe和iv的含义
- Step-by-Step Guide to Setting Up an R-Hadoop System
- 64位Win7安装Oracle12C临时位置权限错误解决方案
- 【LEETCODE】204-Count Primes
- ZxingUtil二维码 封装
- SQL server学习笔记之数据库启动登陆,创建和维护
- UILabel
- MFC Ribbon界面各部分的名字
- 构建兼容浏览器的Angularjs web应用
- 每隔五秒执行一次 共十次 模拟骰子的投掷
- 关于ARM交叉编译工具出现:assertion fail elf32-arm.c:12387 的错误解决办法。
- Openstack Kilo后台命令练习