S Zapata - 3 months ago 14x

Java Question

So I have to write a program that will compute the first 1000 prime numbers and store them into an array, print out the first 50 of those prime numbers, prompt the user to enter an integer less than 1000 and check if its prime, if it is not prime then it will display the integer's smallest factors in increasing order.

I have the code sort of broken up now with certain pieces done, but cant quite figure out the first part that computes the 1000 prime numbers and stores it into an array. Then not sure how to limit the printing of the prime numbers in that array to only the first 50 elements.

The code I have now is below, any help would be much appreciated!

`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++;

}

Answer

You have a method `printPrimeNumbers`

that generates the first x prime numbers. All you need to do is change that logic to store the numbers in an array instead of printing them. I did that and fixed a couple of errors in the method:

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

Then to print the elements is very simple:

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

Source (Stackoverflow)

Comments