
编写JAVA程序,计算小于一个整数的全部素数并输出.
1个回答
展开全部
此算法很快,求2,000,000以内的素数个数只要半秒,全部打印也只要5秒。
static
void
testPrime(int
MAX)
{
long
start
=
System.currentTimeMillis();
//int
MAX
=
2000000;
BitSet
count
=
new
BitSet(MAX
+
1);
for
(int
i
=
2;
i
<=Math.sqrt(MAX);
i++)
{
int
val
=
i
*
2;
while
(val
<=
MAX
)
{
if(!count.get(val)){
count.set(val);
}
val
+=
i
;
}
}
int
counter
=
0;
for(int
i=2
;i<=
MAX;i++){
if(!count.get(i)){
System.out.println(i);
counter++;
}
}
long
end
=
System.currentTimeMillis();
System.out.println("testPrime
took
"
+
(end
-
start)
+
"
ms");
System.out.println("sum:"
+
counter);
static
void
testPrime(int
MAX)
{
long
start
=
System.currentTimeMillis();
//int
MAX
=
2000000;
BitSet
count
=
new
BitSet(MAX
+
1);
for
(int
i
=
2;
i
<=Math.sqrt(MAX);
i++)
{
int
val
=
i
*
2;
while
(val
<=
MAX
)
{
if(!count.get(val)){
count.set(val);
}
val
+=
i
;
}
}
int
counter
=
0;
for(int
i=2
;i<=
MAX;i++){
if(!count.get(i)){
System.out.println(i);
counter++;
}
}
long
end
=
System.currentTimeMillis();
System.out.println("testPrime
took
"
+
(end
-
start)
+
"
ms");
System.out.println("sum:"
+
counter);
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询