leetcode count pirmes
来源:互联网 发布:与知否一样好看的小说 编辑:程序博客网 时间:2024/06/15 06:17
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.
传统方法会出现TLC,转载一个埃拉托斯特尼筛法Sieve of Eratosthenes,这个算法的过程如下,我们从2开始遍历到根号n,先找到第一个质数2,然后将其所有的倍数全部标记出来,然后到下一个质数3,标记其所有倍数,依此类推,直到根号n,此时数组中未被标记的数字就是质数。
代码如下:
public int countPrimes(int n) { int[] res=new int[n]; int k=(int)Math.sqrt(n); int count=0; for(int i=2;i<=k;i++) { if(isPrime(i)) { for(int j=i*i;j<n;j+=i) { res[j-1]=1; } } } for(int i=1;i<res.length;i++) { if(res[i]==0) count++; } return count;}public boolean isPrime(int num){ int k=(int)Math.sqrt(num); for(int i=2;i<=k;i++) { if(num%i==0) return false; } return true;}
0 0
- leetcode count pirmes
- 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
- LeetCode: Count and Say
- LeetCode - Count and Say
- [LeetCode] Count and Say
- Count and Say 【leetcode】
- [LeetCode] Count and Say
- Leetcode Count and Say
- LeetCode Count and Say
- js内存分配详解
- linux命令学习之eval
- 一行显示多个div 并居中显示
- Onethink 前台编辑器调用
- Android之AlarmManager(全局定时器/闹钟)指定时长或以周期形式执行某项操作
- leetcode count pirmes
- 分析 SlideMenu 类的实现
- eclipse使用generator生成文件路径报错问题
- ImageLaod的用法总结
- 使用java nio 时报 java.nio.channels.CancelledKeyException
- 第十六周项目一-小玩文件(1)
- 麒麟开源堡垒机V1.31b发布,
- openssl&&openssh平滑升级
- cdecl、stdcall、fastcall函数调用约定区别