简体   繁体   中英

Method to fill array with prime numbers in array in java

Write a method that,when given an integer value,checks whether the value is a prime number or not. Using your previous answer, write code that fills an array with the first 20 prime numbers.

I have solved the first part and have a method called checkPrime(int n) and it returns true or false. I am confused in the second part which loops should I use, I was trying to do something like this but got stuck :

public static void fillArray() {
    int[] arr = new arr[20];
    n = 1;

    for (int i = 0; i < 20; i++) {
        if (checkPrime(n) == True) {
            arr[i] = n;
            n++;
        } else {
            n++;
        }
}

Here, if the number isnt prime n is being incremented but we arent checking if its prime again. Any help is appreciated.

You need one variable to hold your position in your output array, and another to increment in your loop to test for primality. And, I would return the int[] I built. And pass the number of desired elements into the function. When it is prime, add it to the array. Loop until your array index equals your array length. And it's int[] (not arr[] ). Like,

public static int[] fillArray(int count) {
    int[] arr = new int[count];
    int n = 0;
    for (int i = 1; n < arr.length; i++) {
        if (checkPrime(i)) {
            arr[n] = i;
            n++;
        }
    }
    return arr;
}

or , if you're using Java 8+, you could use an IntStream with a filter and a limit . Like,

public static int[] fillArray(int count) {
    return IntStream.range(1, Integer.MAX_VALUE)
            .filter(x -> checkPrime(x))
            .limit(count).toArray();
}

just do it like these the i will not increes until the loop find a prine number and add it to the array

public static void fillArray(){
int[] arr = new arr[20];
int n -1;
for ( int i = 0; i < 20; ){
if (checkPrime(n) == True){
arr[i] = n;
n++;
i++;
}else {
n++}
}

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