Count-Primes
2015-06-06 10:55
232 查看
Count Primes
Difficulty:Easy
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:
1. 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?
Code
Java
Runtime: 244 ms
public class Solution { public int countPrimes(int n) { if(n<=2) return 0; boolean[] flag = new boolean ; int result = 1; for(int i = 3; i<n ; i = i+2){ if(!flag[i-1]){ result++; for(int k = 3; k*i < n; k = k+2){ if(!flag[k*i-1]) flag[k*i-1]= true; } } } return result; } }
相关文章推荐
- 开学至此时总结。(月末总结好像一直没写)
- 关于linux中so文件的深入认识
- jaxb工具类
- Flatten Binary Tree to Linked List
- Search-a-2D-Matrix
- R-- Dplyr包
- Linux用户管理(2)
- SVM的两个参数 C 和 gamma
- 在IOS应用中打开另外一个应用
- LeetCode Median of Two Sorted Arrays
- 测试项目注意项
- 使用Ant自动化我们的java项目生成
- 推荐一款非常好用的java反编译工具(转)
- arduino小车
- CGLib与JDK的动态代理
- windows系统中国国内镜像网站上用repo下载Android5.0源码
- c#操作excel全攻略(导入导出) excel表增删改 以及常见问题的处理
- Core Graphics快速入门——从一行代码说起
- 【转】飞凌嵌入式(Forlinx)TE/OK6410内核编译:“make: arm-none-linux-gnueabi-gcc:命令未找到”
- 【android】使用RecyclerView和CardView,实现知乎日报精致布局