找到素数 - >筛选方式

时间:2012-09-26 19:52:04

标签: java algorithm primes sieve-of-eratosthenes

我试了好几次但仍然给了我ArrayOutOfIndex。但我想保存内存,所以我使用

boolean[]isPrime = new boolean [N/2+1];

而不是

boolean[]isPrime = new boolean [N+1];

这给了我第23行和第47行的ArrayOutOfIndex

第23行:

    for (int i = 3; i <= N; i=i+2) {
    isPrime[i] = true;
    }
第47行:

  for (int i = 3; i <= N; i=i+2) {
        if (isPrime[i]) primes++;
  ...
   }

Full code:

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

        if (args.length < 1) {
            System.out.println("Usage: java PrimeSieve N [-s(ilent)]");
            System.exit(0);
        }

        int N = Integer.parseInt(args[0]);

        // initially assume all odd integers are prime

        boolean[]isPrime = new boolean [N/2+1];

        isPrime[2] = true;

        for (int i = 3; i <= N; i=i+2) {
            isPrime[i] = true;
        }

        int tripCount = 0;

        // mark non-primes <= N using Sieve of Eratosthenes
        for (int i = 3; i * i <= N; i=i+2) {

            // if i is prime, then mark multiples of i as nonprime
        if (isPrime[i]) {
          int j = i * i;
          while (j <= N){
            tripCount++;
            isPrime[j] = false;
            j = j + 2*i;
            }
                        }
                                            }

        System.out.println("Number of times in the inner loop: " + tripCount);

        // count and display primes
        int primes = 0;
        if(N >= 2 ){
            primes = 1;
        }
        for (int i = 3; i <= N; i=i+2) {
            if (isPrime[i]) primes++;
            if (args.length == 2 && args[1].equals("-s"))
                ; // do nothing
            else
                System.out.print(i + " ");
        }
        System.out.println("The number of primes <= " + N + " is " + primes);
    }
}

3 个答案:

答案 0 :(得分:1)

当您将数组的大小从[N+1]更改为[N/2+1]时,您还需要更新for循环的最终条件。现在你的for循环一直运行到i=N,所以你在isPrime[i]时尝试i > (N/2+1) ...所以你得到ArrayIndexOutOfBoundsException

改变这个:

for (int i = 3; i <= N; i=i+2) 

到此:

for (int i = 3; i <= N/2; i=i+2) 

答案 1 :(得分:1)

您应该使用相同的索引功能存储和访问数组:isPrime[i/2]

答案 2 :(得分:0)

好吧,例如,如果N = 50,你的isPrime只能容纳26个元素,而你正试图访问3,5..47,49的元素(当然,这是超出界限的)

你可能想要的是在你的循环中使用i/2(作为索引),这样你仍然在迭代数字3,5..47,49,但是你使用矢量的正确索引。