【问题标题】:Does this program use the Sieve of Eratosthenes?该程序是否使用 Eratosthenes 筛?
【发布时间】:2015-02-27 21:50:04
【问题描述】:

我有一个任务如下, : 使用埃拉托色尼筛法找出并打印出从 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" ); 
                    }

                }
            }
      } 
} 

任何帮助都会很好!

【问题讨论】:

  • 怎么回事?你能解释什么是错的吗?
  • 你为什么拒绝我的问题?我认为这是一个非常有效的问题,如果我被投票,如果出现问题,我就不能再问了
  • 你怎么敢认为是我?
  • 它只是在数组中将值声明为 true。
  • 从广场开始就可以了。您也可以通过2*i 前进,而不仅仅是i。然而,你的for 循环有一些有趣的地方,后面跟着both 一个语句和一个块。它不符合格式的建议。

标签: java arrays


【解决方案1】:

问题是您在打印结果之前没有完成标记复合的过程,可能是因为您的循环以一种混乱的方式嵌套。

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);
    }
}

在此示例中,我已将代码移动到执行筛选的循环之外打印素数。

【讨论】:

  • 哦,好吧,它看起来比我的好多了,而且运行起来也更好。是什么让完成了筛子呢?是不是因为你的成绩比我的好?
  • 这是因为在所有“将复合标记为真”工作完成之前,它不会打印任何结果。
  • 好的,非常感谢,这很有意义。有趣的是,简单地移动东西是如何工作的!
猜你喜欢
  • 2014-04-15
  • 1970-01-01
  • 1970-01-01
  • 2013-04-11
  • 2014-01-07
  • 1970-01-01
  • 1970-01-01
  • 2013-05-28
  • 2015-09-06
相关资源
最近更新 更多