简体   繁体   English

根据Eratosthenes的Sieve的Java Prime计算器

[英]Java Prime calculator according to Sieve of Eratosthenes

I've stumbled on the following problem: I have a class to get and print all primes between 1 and N. The N is a parameter which you have to insert by yourself. 我偶然发现了以下问题:我有一个要获取并打印1到N之间的所有素数的类。N是您必须自己插入的参数。 When I insert 10000 for N, the code works and prints out all primes out from 2 to the closest prime to N. 当我为N插入10000时,代码会工作并打印出所有素数(从2到最接近N的素数)。

When I insert 40000 the code still works. 当我插入40000时,代码仍然有效。 When I insert 50000 (or higher), the code gives an ArrayOutOfBoundsException. 当我插入50000(或更高版本)时,代码给出ArrayOutOfBoundsException。 Why? 为什么?

This is the code I use: 这是我使用的代码:

  ArrayList<Integer> priemGetallen = priemGetallen(n);
        for (Integer i : priemGetallen) {
              System.out.println(i);
        }

And uses 并使用

ArrayList<Integer> priemgetallen = new ArrayList<Integer>();

for(int i = 2; i < n; i++){
    priemgetallen.add(i);
}

for (int i = 2; i < n; i++) {
    for (int j = i; j * i <= n; j++) {
      if((j*i) < priemgetallen.size()){
          priemgetallen.remove(j*i);
        }
        }
   }
   return priemgetallen;
  }

The point "priemgetallen.remove(j*i)" is where I receive the error. 我收到错误的地方是“ priemgetallen.remove(j * i)”。

I'd really appreciate it if someone can tell me why this doesn't work for all N's bigger then approx. 如果有人能告诉我为什么这不适用于所有大于N的N,我将非常感激。 40000. 40000。

Thanks in advance! 提前致谢!

The maximum value a Java int can hold is 2,147,483,647, so j * i is overflowing when i and j reach 46,341. Java int可以容纳的最大值是2,147,483,647,因此当ij达到46,341时j * i溢出。

To extend the range, change the types of i , j and n to long . 要扩展范围,请将ijn的类型更改为long

See How does Java handle integer underflows and overflows and how would you check for it? 请参阅Java如何处理整数下溢和溢出以及如何检查整数?

PS You'll also need to change priemgetallen into an array list of Long rather than Integer . PS您还需要将priemgetallen更改为Long而不是Integer的数组列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM