gpt4 book ai didi

java - 该程序是否使用埃拉托斯特尼筛法?

转载 作者:行者123 更新时间:2023-12-01 22:26:04 24 4
gpt4 key购买 nike

我的任务如下,:使用埃拉托色尼筛法查找并打印出 1 到 1000 之间的所有素数。

遵循与此类似的过程:

  1. 按顺序写下要考虑的所有数字。
  2. 划掉 1,因为它不被视为素数。
  3. 转到下一个未划掉的数字;保留它,但划掉该数字的所有倍数。
  4. 重复步骤 3,直到传递的数字是所考虑的最大数字的一半。此时,所有未划掉的数字都是所需的素数。

您的算法可能与上面的算法略有不同,但速度很重要。

我使用我所拥有的数学和数组知识编写了这个程序,但是当我研究 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com