Polina Trotsenko
Polina Trotsenko

Reputation: 107

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;
}

Upvotes: 2

Views: 14175

Answers (6)

Chris Sharp
Chris Sharp

Reputation: 1995

You are using the wrong index for your primes array.

Change this code:

if (prime) {
    primes[i] = isPrime;
    ncounter++;
}

to this:

if (prime) {
    primes[ncounter] = isPrime;
    ncounter++;
}

Upvotes: 0

Tanuj Yadav
Tanuj Yadav

Reputation: 1297

The problem with your code is that you have fixed the size of array to be n. And you are storing the found prime at ith index, but the i can exceed the value of n, thats why you are getting array out of bounds exception.

Replace

primes[i] = isPrime

with

primes[ncounter] = isPrime

Upvotes: 0

RamPrakash
RamPrakash

Reputation: 1834

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;
}

Upvotes: 1

user15495739
user15495739

Reputation:

A prime number is a natural number greater than 1 that is not a product of two smaller natural numbers.

Using Java 8 you can find these numbers as follows:

int n = 10;
int[] primes = IntStream
        // infinite sequential ordered IntStream
        // starting at 2 in increments of 1
        .iterate(2, i -> i + 1)
        // filter prime numbers
        .filter(i -> IntStream
                // numbers from 2 to current number
                .range(2, i)
                // do not divide the current
                // number without a remainder
                .allMatch(j -> i % j != 0))
        // first 'n' prime numbers
        .limit(n)
        // return an array
        .toArray();

// output
System.out.println(Arrays.toString(primes));
// [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

Upvotes: 0

Vince Pergolizzi
Vince Pergolizzi

Reputation: 6584

In your initial solution, you were updating the counter i regardless if you found a new prime. This causes it to get ahead of the max size of the array. You can just use the ncounter variable and a while loop like so:

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;
}

Upvotes: 0

Jarvis
Jarvis

Reputation: 8564

Replace

primes[i] = isPrime;

by

primes[ncounter] = isPrime;

This counter increments only when you put an element in the array, whereas, the variable i keeps on increasing and can also become greater than n since there is no condition on its limit in the for loop.

Upvotes: 1

Related Questions