[英]Does this program use the Sieve of Eratosthenes?
我有一個作業,如下所示:使用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" );
}
}
}
}
}
你能幫忙的話,我會很高興!
問題在於,您在打印出結果之前沒有完成標記合成物的過程,這可能是因為您的循環是以一種混亂的方式嵌套的。
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);
}
}
在此示例中,我已移動代碼以在執行篩分的循環外部打印質數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.