首页 > 代码库 > LeetCode-Count Primes
LeetCode-Count Primes
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.
Analysis:
See hint in leetcode.
Solution:
public class Solution { public int countPrimes(int n) { if (n<=2) return 0; boolean[] marked = new boolean[n]; for (int i=3;i*i<n;i+=2) if (!marked[i]){ // i*i+(2*k+1)*i = i*(i+1+2k) is an even value because (i+1) is even. // We can skip all such number by increasing value by 2*i every time. for (int value = http://www.mamicode.com/i*i;valuei){ marked[value]=true; } } int count = 1; for (int i=3;i<n;i+=2) if (!marked[i]){ count++; } return count; }}
LeetCode-Count Primes
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。