senpaimaster - 8 months ago 57

Java Question

Okay my issue is less of how to figure out if a number is prime, because I think I figured that out, but more of how to get it to display properly.

Here's my code:

`public static void main(String[] args) {`

// Declare Variables

int randomNumbers = 0;

int sum = 0;

//Loop for number generation and print out numbers

System.out.print("The five random numbers are: ");

for (int i = 0; i <= 4; i++)

{

randomNumbers = (int)(Math.random()*20);

sum += randomNumbers;

if (i == 4) {

System.out.println("and " + randomNumbers + ".");

}

else {

System.out.print(randomNumbers + ", ");

}

}

//Display Sum

System.out.println("\nThe sum of these five numbers is " + sum + ".\n");

//Determine if the sum is prime and display results

for(int p = 2; p < sum; p++) {

if(sum % p == 0)

System.out.println("The sum is not a prime number.");

else

System.out.println("The sum is a prime number.");

break;

}

}

}

Now my problem is, if the number ends up being something like 9, it'll say it is a prime number, which it is not. I think the issue is that the break is stopping it after one loop so it's not incrementing variable p so it's only testing dividing by 2 (I think). But if I remove the break point it will print out "The sum is/is not a prime number" on every pass until it exits the loop. Not sure what to do here.

Answer

Your method for finding if your number is prime is the correct method. To make it so that it does not consistently print out whether or not the number is prime, you could have an external variable, which represents whether or not the number is prime.

Such as

```
boolean prime = true;
for (int p = 2; p < sum; p++) {
if (sum % p == 0) {
prime = false;
break;
}
}
if (prime)
System.out.println("The sum is a prime number.");
else
System.out.println("The sum is not a prime number.");
```

By doing this method the program will assume the number is prime until it proves that wrong. So when it finds it is not prime it sets the variable to false and breaks out of the loop.

Then after the loop finishes you just have to print whether or not the number was prime.

A way that you could make this loop faster is to go from when p = 2 to when p = the square root of sum. So using this method your for loop will look like this:

```
double sq = Math.sqrt((double)sum);
for (int p = 2; p < sq; p++) {
//Rest of code goes here
}
```

Hope this helps

Source (Stackoverflow)