Find the first n prime numbers and store them in an array

I need to find the first n prime numbers and store them in the array primes. With the help of stuff I found on stackoverflow I succeeded in find the first n numbers, but when I try to store them in the array, I get the ArrayIndexOutOfBoundsException

public static int[] firstNPrimes(int n) {
    int[] primes = new int[n];
    int ncounter = 0;
    int isPrime = 2;
    for (int i = 0; ncounter < n; i++) {
        boolean prime = true;
        for (int j = 2; j < isPrime; j++) {
            if (isPrime % j == 0) {
                prime = false;
                break;
            }
        }
        if (prime) {
            primes[i] = isPrime;
            ncounter++;
        }
        isPrime++;
    }
    return primes;
}

Answer

Issue is with primes[i] = isPrime; it should be primes[ncounter] = isPrime;

You don’t need i variable at all, use while loop instead:

public static int[] firstNPrimes(int n) {
    int[] primes = new int[n];
    int ncounter = 0;
    int isPrime = 2;
    while (ncounter < n) {
        boolean prime = true;
        for (int j = 2; j < isPrime; j++) {
            if (isPrime % j == 0) {
                prime = false;
                break;
            }
        }
        if (prime) {
            primes[ncounter] = isPrime;
            ncounter++;
        }
        isPrime++;
    }
    return primes;
}

Leave a Reply

Your email address will not be published. Required fields are marked *