leetcode-204. Count Primes
2016-04-27 21:54
253 查看
Description:
Count the number of prime numbers less than a non->negative number, n.
Credits:
Special thanks to @mithmatt for adding this problem and >creating all test cases.
Hint:
Let’s start with a isPrime function. To determine if a >number is prime, we need to check if it is not divisible by >any number less than n. The runtime complexity of >isPrime function would be O(n) and hence counting the >total prime numbers up to n would be O(n2). Could we >do better?
As we know the number must not be divisible by any >number > n / 2, we can immediately cut the total >iterations half by dividing only up to n / 2. Could we still >do better?
思路:如果用传统的从下往上遍历依次判断,数字大了显然不行。改进方法:空间换时间,给n个数设标志位,从小的开始依次乘积改标志位。直接看代码吧:
Count the number of prime numbers less than a non->negative number, n.
Credits:
Special thanks to @mithmatt for adding this problem and >creating all test cases.
Hint:
Let’s start with a isPrime function. To determine if a >number is prime, we need to check if it is not divisible by >any number less than n. The runtime complexity of >isPrime function would be O(n) and hence counting the >total prime numbers up to n would be O(n2). Could we >do better?
As we know the number must not be divisible by any >number > n / 2, we can immediately cut the total >iterations half by dividing only up to n / 2. Could we still >do better?
思路:如果用传统的从下往上遍历依次判断,数字大了显然不行。改进方法:空间换时间,给n个数设标志位,从小的开始依次乘积改标志位。直接看代码吧:
class Solution { //传统的遍历判断是否是素数效率太低了,只能用空间换时间 public: int countPrimes(int n) { vector<bool> isPrime(n+1,true); int primeNum = 0; int upperBound = sqrt(n); for(int i=2;i<n;i++) { if(isPrime[i]) { primeNum++; if(i > upperBound) { continue; } //小于n的能组合分解的都为合数 for(int j = i;i*j < n;j++) { isPrime[i*j] = false; } } } return primeNum; } };
相关文章推荐
- Java Excel API的学习
- wamp集成环境虚拟主机的配置
- STM32F4跑马灯实验(原子)
- java_web第四课 DAO模式与多请求处理
- 计蒜客 delightful world
- PullToRefreshListView的下拉刷新上拉加载更多问题
- 链表操作
- 使用httpclient提交数据
- java执行流程图
- 2015级C++第10、11周补充实践项目 继承和派生
- 使用反射生成并操作对象
- qt学习笔记(七)之数据库简介(所有支持数据库类型的列表)
- 冲刺第九天
- ajax
- 字符串匹配—KMP 扩展KMP Manacher
- Flask -- 使用数据库(Sqlite3)、用户注册、登录注销、修改密码
- 字串的连接最长路径查找(sort函数实现)
- 3牌递归
- SecureCRT 使用技巧
- Flyway学习笔记