我的作业如下, :使用Eratosthenes的筛子找到并打印出从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" );
}
}
}
}
}
任何帮助都会很好!
答案 0 :(得分:3)
问题是你在打印结果之前没有完成标记复合的过程,可能是因为你的循环以一种混乱的方式嵌套。
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);
}
}
在这个例子中,我已经移动代码来打印执行筛子的循环之外的素数。