简体   繁体   中英

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):

   // 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

*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". When I press on that, this is what I get:

primes[j] = i; in Main.main(String[]) (filter: 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.

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. And in the inner loop, k should start at 2 , not 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:

104743

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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