Confused on Prime numbers
EDIT: I figured it out finally, I actually did need to use a for loop. Here's my solution to my own problem:
Code Java:
System.out.println("Enter a positive integer: ");
int num = input.nextInt();
int i;
for (i = 2; i < num; i++) {
int n = num % i;
if (n == 0) {
System.out.println("not prime");
break;
}
}
if (i == num) {
System.out.println("Prime");
}
Hello, I want to compute whether a number is prime or not but I can't seem to do it. I don't think it's that hard because I'm new to Java but I am stumped.
I can't seem to make a given input be divisible by only 1 and the number itself.
Here's what I wrote so far using If-else statements:
Code Java:
String pnS = JOptionPane.showInputDialog("Enter a positive integer: ");
int p = Integer.parseInt(pnS); //user enters an integer
if (p < 2) {
JOptionPane.showMessageDialog(null, "not prime");
}
else if ((p % 2 == 0) || (p % 3 == 0)) {
JOptionPane.showMessageDialog(null, "not prime");
}
else {
JOptionPane.showMessageDialog(null, "prime!");
}
How would I show whether it's prime or not? I've searched around on the internet and found people using for loops, which i know how to do but I don't see it applying in my case because they just list prime numbers in a certain number of iterations while I'm trying to figure out whether a certain number is prime or not.
Thank you.