题:https://leetcode.com/problems/count-primes/description/
题目
Count the number of prime numbers less than a non-negative number, n.
Example:
Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
题目大意
统计 小于n的质数和。
思路
埃拉托斯特尼筛法
参考:https://blog.csdn.net/o83290102o5/article/details/79491834
note: 只用判断 若 小于 sqrt(n)的数都扫描过了,那 sqrt(n) -> n 的数不用扫描。
class Solution {
public int countPrimes(int n) {
boolean[] notPrimes = new boolean[n];
int sqrtn = (int)Math.sqrt(n);
for(int i = 2;i <= sqrtn;i++){
if(notPrimes[i])
continue;
for(int j = i*i;j<n;j+=i)
notPrimes[j] = true;
}
int cnt = 0;
for(int i = 2;i<n;i++)
if(!notPrimes[i])
cnt++;
return cnt;
}
}
将 统计循环部分简化
class Solution {
public int countPrimes(int n) {
boolean[] notPrimes = new boolean[n];
int sqrtn = (int)Math.sqrt(n);
int cnt = 0;
for(int i = 2;i <n;i++){
if(notPrimes[i])
continue;
cnt++;
for(long j = (long) (i) * i;j<n;j+=i)
notPrimes[(int)j] = true;
}
return cnt;
}
}
1233

被折叠的 条评论
为什么被折叠?



