简体   繁体   English

用Java中的数组中的质数填充数组的方法

[英]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. 使用您先前的答案,编写代码,以前20个质数填充数组。

I have solved the first part and have a method called checkPrime(int n) and it returns true or false. 我已经解决了第一部分,并有一个称为checkPrime(int n)的方法,它返回true或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. 在这里,如果数字不是素数,则n将增加,但我们不会再次检查其素数。 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. 并且,我将返回我构建的int[] 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[] ). 它是int[] (不是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 . 或者 ,如果您使用的是Java 8+,则可以使用带有filterlimitIntStream 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 像这样做,直到循环找到一个prine号并将其添加到数组中,我才会递增

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

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

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