如何计算1000个素数并存储到数组中

时间:2016-06-23 23:48:49

标签: java arrays

所以我必须编写一个程序来计算前1000个素数并将它们存储到一个数组中,打印出前50个素数,然后提示用户输入一个小于1000的整数并检查它是否是素数,如果它不是素数,那么它将按递增顺序显示整数的最小因子。

我已经完成了某些部分的代码分解,但是不能完全弄清楚计算1000个素数的第一部分并将其存储到数组中。然后我不知道如何将该数组中素数的打印限制为仅前50个元素。

我现在的代码如下,非常感谢任何帮助!

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    //print out the first 50 primes
    System.out.println("The first 50 prime numbers are: \n");
    printPrimeNumbers(50);

    //integer that will be checked for being prime
    System.out.println("Please enter an integer:");
    int integer = input.nextInt();

    //if integer not prime then print out its smallest factors
    if(isPrime(integer) == false){
    int i = 2;
    String s = " ";

    //code for finding smallest factors
    while (integer != 1){
        if (integer % i == 0){
            s = s + ", " + i;
            integer = (integer / i);
            i = 2;
        }
        else {
            i++;
        }
    }

    System.out.print("The smallest factors are " + s.substring(2) + ".");
}

//checks whether integer is prime
public static boolean isPrime(int number){

    for (int divisor = 2; divisor <= (number/2); divisor++){
        if (number % divisor == 0){
            return false; 
        }
    }

    return true;
}

//needs to print first 50 of the 1000 prime numbers computed
public static void printPrimeNumbers(int numberOfPrimes){
    final int NUMBER_OF_PRIMES_PER_LINE = 10;
    int count = 0;
    int number =2;

    while(count < numberOfPrimes) {
        if(isPrime(number)){
            count++;
        }
        if(count % NUMBER_OF_PRIMES_PER_LINE == 0){
            System.out.printf("%-5s\n", number);
        }
        else
            System.out.printf("%-5s\n", number);
    }
    number++;
}

1 个答案:

答案 0 :(得分:0)

您有一个方法printPrimeNumbers,可生成前x个素数。您需要做的就是更改逻辑以将数字存储在数组中而不是打印它们。我这样做并修复了方法中的一些错误:

private static final int NUM_PRIMES = 1000;
private static final int FIRST_PRIME = 2;
private int[] primes;

public static void generatePrimes() {

    //initialize variables
    primes = new int[NUM_PRIMES];
    int count = 0;
    int number = FIRST_PRIME;

    //loop until the array is full
    while(count < NUM_PRIMES) {

        //if the number is prime
        if(isPrime(number)){

            //add it to the array and increment the array index / prime count
            primes[count] = number;
            count++;
        }

        //increment the number being checked
        number++;
    }
}

然后打印元素非常简单:

for (int i = 0; i < primes.length; i++) {
 System.out.print(primes[i]);
}