简体   繁体   English

第10001个素数是多少? 为什么我的 Java 解决方案会给出错误 ArrayIndexOutOfBoundsException?

[英]What is the 10001st prime number? Why does my Java solution give the error ArrayIndexOutOfBoundsException?

So this is my Java code for Project Euler #7(description of problem commented out in code):所以这是我的项目 Euler #7 的 Java 代码(代码中注释掉的问题描述):

   // By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
   // What is the 10001st prime number?
    boolean isPrime = true;
    long [] primes = new long[10001];
    int j = 0;
    while (j < 10001){
        for (long i = 2; i < 1000000000000000L; i++) {
            for (long k = i; k < i / 2; k++) {
                if (i % k == 0) {
                    isPrime = false;
                    break;
                }
            }
            if (isPrime) {
                primes[j] = i;
                j++;
            }
        }
    }
    System.out.println(primes[10000]);

When I run this code, this is what I get as a result:当我运行此代码时,结果如下:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10001线程“主”java.lang.ArrayIndexOutOfBoundsException 中的异常:10001

*at vasila.mir.Main.main(Main.java from InputFileObject:22)*

When I press on the ArrayIndexOutOfBoundsException error it gives me this "Find why 'j' could be 10001".当我按下ArrayIndexOutOfBoundsException错误时,它给了我这个“找出为什么 'j' 可能是 10001”。 When I press on that, this is what I get:当我按下它时,这就是我得到的:

primes[j] = i;素数[j] = i; in Main.main(String[]) (filter: 10001)在 Main.main(String[]) (过滤器: 10001)

I don't understand what that means, and it doesn't really help me.我不明白这意味着什么,它并没有真正帮助我。 What could be the problem with my code?我的代码可能有什么问题?

If your for (long i = 2; i < 1000000000000000L; i++) finds more that 10001 primes, your outer loops condition is never checked in time to finish the program.如果您的for (long i = 2; i < 1000000000000000L; i++)找到超过 10001 个素数,则永远不会及时检查您的外部循环条件以完成程序。

You should combine the loops你应该结合循环

Change改变

while (j < 10001){
    for (long i = 2; i < 1000000000000000L; i++) {

to

for (long i = 2; i < 1000000000000000L && j < 10001; i++) {

You should also reset isPrime to true at the start of the outer for loop.您还应该在外部 for 循环开始时将isPrime重置为true And in the inner loop, k should start at 2 , not i .在内部循环中, k应该从2开始,而不是i

The following works:以下作品:

long [] primes = new long[10001];
int j = 0;
for (long i = 2; i < 1000000000000000L && j < 10001; i++) {
    boolean isPrime = true;
    for (long k = 2; k <= i / 2; k++) {
        if (i % k == 0) {
            isPrime = false;
            break;
        }
    }
    if (isPrime) {
        primes[j] = i;
        j++;
    }

}
System.out.println(primes[10000]);

Output: Output:

104743

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

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