if (a == 0) {
break;
}
else {
System.out.println(base+" is a prime number, so it has no factors");
break;
}
No matter what, you're breaking out of the loop on the first increment. Even if you removed the break;
from the else
block, you are still displaying whether or not the number is prime too early. You need to decide that after all of the iterations are completed.
So, consider a boolean
variable to keep track of whether or not the number has at least one factor in it:
boolean isPrime = true; // true unless proven otherwise
for (int i = 2; i < base; i++) {
int a = base % i;
if (a == 0) {
isPrime = false; // has factor so it's not prime
break;
}
}
if (isPrime) {
System.out.println(base + " is a prime number, so it has no factors");
} else {
System.out.println(base + " is a composite number: "); // say it's not prime
// then display the factors
for (int i = 3; i < base; i++) {
int res = base % i;
if (res == 0) {
int fac = base / i;
System.out.println(i + " and " + fac + " are factors of " + base);
}
}
}
Here is a pastie to this entire class.