题目如下:
Description:
Count the number of prime numbers less than a non-negative number, n.
一开始用的方法入下,结果运算时间太大
public class Solution {public int countPrimes(int n) {
boolean mark = true;
int count=0;
for(int i=2;i<n;i++)
{
for(int m=2; m<=Math.sqrt(i);m++ )
{
mark = true;
if(i%m==0)
{
mark =false;
break;
}
}
if(mark)
{
count++;
}
}
return count;
}
}
后来改成如下写法,通过
public class Solution {
public int countPrimes1(int n)
{
boolean bool[] = new boolean[n];
if (n <= 2) return 0;
int counter = n-2;
int j = 0;
for (int i = 2; i <= Math.floor(Math.sqrt(n)); i++) {
j = i + i;
if (!bool[i])
{
while (j < n) {
if (!bool[j]) {
bool[j] = true;
counter --;
}
j = j + i;
}
}
}
return counter;
}
本文介绍了一种改进的质数计数方法,通过优化循环和条件判断,显著减少了运算时间。从基本的质数判断算法出发,采用更高效的筛选方式,实现快速计算指定范围内所有质数的数量。
1177

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



