【问题标题】:Java: ArrayOutofBounds Exception when trying to count primes using SieveJava:尝试使用 Sieve 计算素数时出现 ArrayOutofBounds 异常
【发布时间】:2014-11-18 21:19:26
【问题描述】:

我的代码编译没有错误,但在我的输出中,我得到了第 37 行的 ArrayOutofBoundsException。除了主计数器之外,一切正常。谁能看到我在这段代码中哪里出错了?主计数器在我的另一个程序中工作。

import java.util.Scanner;

public class Sieve {
public static void main(String[] args) {

    //get ceiling on our prime numbers
    int N;
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter the prime number ceiling: ");
    N = sc.nextInt();
    sc.close();

    //init our numbers array, where true denotes prime
    boolean[] isPrime = new boolean[N];
    isPrime[0] = false;
    for (int c = 1; c < N; c++) {
        isPrime[c] = true;

    }

    //check every number >= 2 for primality
    //first loops, checks to see is numbers are marked
    for (int i = 2; i <= N; i++) {
        if (isPrime[i-1]) {
            System.out.print(i + " ");

            //cross off all subsequent mutliples of
            //second loop, marks all multiples of number
            for (int j = i * 2; j <= N; j += i) {
                isPrime[j-1] = false;
            }
        }
    }
    //counts primes
    int primes = 0;
    for (int c = 0; c <= N; c++) {
        if (isPrime[c]); //error here
        primes++;
    }
    //prints # of primes
    System.out.println(" ");
    System.out.println("The number of primes <= " + N + " is " + primes);
}
}

【问题讨论】:

  • 尝试不带=c &lt; N。请记住,数组在 Java 中是从零开始的

标签: java sieve-of-eratosthenes


【解决方案1】:

你的 for 循环条件不好

for (int c = 0; c <= N; c++) {

应该是

for (int c = 0; c < N; c++) {

因为你有一个维度为 N 的数组,并且 cointng 从 0 开始。


for (int c = 1; c < N; c++) {
        isPrime[c] = true;

}

此代码将所有数字设置为素数。 您应该做的是将每个数字设置为素数,然后将数字的每个倍数设置为非素数。

应该是这样的

Arrays.fill(isPrime, true);
isPrime[0] = false;
for (int x = 1, x < N; x++) {
   for (int y = x; y < N; y+=x) {
      isPrime[y] = false;
   }
}

这应该是真正的筛算法。参考https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

【讨论】:

  • 修复了一半,谢谢!但是,现在它说素数的数量是 N 是多少。有什么想法吗?
  • 还添加了主要解决方案
猜你喜欢
  • 1970-01-01
  • 2017-09-08
  • 1970-01-01
  • 1970-01-01
  • 2012-09-05
  • 2012-09-10
  • 1970-01-01
  • 2017-08-13
  • 1970-01-01
相关资源
最近更新 更多