Leetcode:204. Count Primes 求素数的优化问题
来源:互联网 发布:北京seo田野博客 编辑:程序博客网 时间:2024/05/16 07:14
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.
最常见的一种代码。
int count = 0; for (int i = 2; i <n; i++) { int j = 0; for ( j = 2; j <=Math.sqrt(i); j++) { if (i%j == 0) { break; } } if (j > Math.sqrt(i)) { count++; } } return count;
但是在测试的时候会报错。因为当输入1500000的时候系统运行超时,可见需要改进。
一种改进方法如下:
时间复杂度:
时间复杂度仅有O(nloglogn)
利用厄拉多塞筛法
厄拉多塞筛法的步骤:建立从2到n的集合G={2, 3, 4, …, n},每次从集合中取出最小的数i,这个数就是质数;然后将数i*i从集合中删除。得到一个新的集合G’,重复上述步骤直到集合为空,就取出了所有质数。
举例一个集合{2, 3, 4, …, 12}:
stp1:最小值为2,取出2并删除2,4,6,8,10,12,集合变为{3, 5, 7, 9, 11};
stp2:最小值为3,取出3并删除3,6,9,集合变为{5, 7, 11}
代码:
别人写的:
if (n < 3) return 0; boolean[] f = new boolean[n]; int count = n / 2; for (int i = 3; i * i < n; i += 2) { if (f[i]) continue; for (int j = i * i; j < n; j += 2 * i) { if (!f[j]) { --count; f[j] = true; } } } return count;
阅读全文
0 0
- Leetcode:204. Count Primes 求素数的优化问题
- [LeetCode] Count Primes - 素数系列问题
- LeetCode 204. Count Primes(统计素数)
- leetcode 204. Count Primes-素数统计
- [LeetCode]Count Primes素数个数
- leetcode Count Primes 素数个数
- LeetCode OJ 之 Count Primes(计算素数的个数)
- leetcode---Count Primes---素数筛法的改进
- 204.leetcode Count Primes (easy)[素数 数学观察]
- Count Primes 筛选法求素数
- 【LeetCode】204.Count Primes
- [leetcode] 204.Count Primes
- LeetCode 204. Count Primes
- Leetcode 204. Count Primes
- [LeetCode]204. Count Primes
- 204. Count Primes LeetCode
- LeetCode *** 204. Count Primes
- LeetCode 204. Count Primes
- jvm内存泄露解析以及相应的简单处理
- windows远程磁盘容量监控
- ELK第一篇:Elasticsearch安装
- simpledateformat非线程安全问题
- 剑指offer----链表中环的入口节点----java实现
- Leetcode:204. Count Primes 求素数的优化问题
- Angular 4 多级表格,层级表格树
- Android二维码扫一扫功能实现,解析Zxing源码的执行过程
- LinuxTomcat(war包解压)部署,解压后,项目未更新至新的版本的问题记录
- [codeplus 11月月赛]T2 timber
- 手撸一个简易Android数据库框架
- Unity Shader:实现菲涅尔+色散效果以及相关原理解析
- ...
- css 段落属性