LeetCode-Count Primes
Posted LiBlog
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 = i*i;value<n;value+=2*i){ marked[value]=true; } } int count = 1; for (int i=3;i<n;i+=2) if (!marked[i]){ count++; } return count; } }
以上是关于LeetCode-Count Primes的主要内容,如果未能解决你的问题,请参考以下文章