您的位置:首页 > 其它

Leetcode:204. Count Primes 求素数的优化问题

2017-11-27 11:54 239 查看
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.

最常见的一种代码。

int count = 0;
for (int i = 2; i <n; i++)
{
int j = 0;
for ( j = 2; j <=Math.sqrt(i); j++)
{
if (i%j == 0)
{
break;
}
}
if (j > Math.sqrt(i))
{
count++;
}

}
return count;


但是在测试的时候会报错。因为当输入1500000的时候系统运行超时,可见需要改进。

一种改进方法如下:

时间复杂度:

时间复杂度仅有O(nloglogn)

利用厄拉多塞筛法

厄拉多塞筛法的步骤:建立从2到n的集合G={2, 3, 4, …, n},每次从集合中取出最小的数i,这个数就是质数;然后将数i*i从集合中删除。得到一个新的集合G’,重复上述步骤直到集合为空,就取出了所有质数。

举例一个集合{2, 3, 4, …, 12}:

stp1:最小值为2,取出2并删除2,4,6,8,10,12,集合变为{3, 5, 7, 9, 11};

stp2:最小值为3,取出3并删除3,6,9,集合变为{5, 7, 11}

代码:

别人写的:

if (n < 3)
return 0;

boolean[] f = new boolean
;
int count = n / 2;
for (int i = 3; i * i < n; i += 2) {
if (f[i])
continue;

for (int j = i * i; j < n; j += 2 * i) {
4000
if (!f[j]) {
--count;
f[j] = true;
}
}
}
return count;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: