作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我的任务如下,:使用埃拉托色尼筛法查找并打印出 1 到 1000 之间的所有素数。
遵循与此类似的过程:
您的算法可能与上面的算法略有不同,但速度很重要。
我使用我所拥有的数学和数组知识编写了这个程序,但是当我研究 Sieve 时,我不知道这是否是方法。
public class PrimeSieve
{
public static void main( String[] args)
{
int max=1000;
calcPrimes( max );
}
public static void calcPrimes( int max )
{
// each boolean value indicates whether corresponding index
// position is composite (non-prime)
boolean[] array = new boolean[max +1 ];
// mark composites as true
for (int i = 2; i <= (int) Math.sqrt( max ); i++)
{
for (int j = i*i; j <= max; j += i) array [j ] = true;
{
// print indexes with corresponding false values
for (int k = 2;k <= max; k++)
{
if ( !array[ k ] )
System.out.format( k + "\n" );
}
}
}
}
}
任何帮助都会很好!
最佳答案
问题是您在打印结果之前没有完成标记复合的过程,可能是因为您的循环以一种困惑的方式嵌套。
public static void calcPrimes(int max) {
// each boolean value indicates whether corresponding index
// position is composite (non-prime)
boolean[] array = new boolean[max + 1];
// mark composites as true
for (int i = 2; i <= (int) Math.sqrt(max); i++) {
for (int j = i*i; j <= max; j += i) array[j] = true;
}
// print indexes with corresponding false values
for (int k = 2; k <= max; k++) {
if (!array[k]) System.out.println(k);
}
}
在此示例中,我已移动代码以在执行筛子的循环之外打印素数。
关于java - 该程序是否使用埃拉托斯特尼筛法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28774929/
我是一名优秀的程序员,十分优秀!