I apologize if this is a dumb question, I'm pretty new to Java, but I can't figure out why my mod operator based primality test for numbers 1-100 stops at 1. I've tried following my code and I don't understand why it fails to continue to the last else statement when possiblePrime = 2.
It should just take possiblePrime = 2 through the if and else if statements all the way to the last else statement and print "2 is a prime." and then continue on to possiblePrime = 3, but instead it goes through the loops as it should when possiblePrime = 1, as it is when it is initialized at the start, and then stops entirely once possiblePrime is incremented at the end of the last else statement, solely printing "1 is a prime."
Thank you for any help you might be able to offer, it is much appreciated! I am definitely racking my brain trying to figure this out, and I'm almost 100% sure it is some stupid and obvious mistake I'm just not seeing.
public class PrimeFind {
public static void main(String[] args){
int possiblePrime = 1;
for(int i = 1 ; i <= 100 ; i++){
int possibleDivisor = 1;
if(possiblePrime%possibleDivisor != 0){
possibleDivisor++;
}
else if(possiblePrime != possibleDivisor){
possiblePrime++;
}
else{
System.out.println(possiblePrime + " is a prime.");
possiblePrime++;
}
}
}
}
You are setting
possibleDivisor = 1
inside the for loop. hence it will always equal 1. This in turn will make the modulo operation equal to 0 in every case. The possiblePrime will always be different from the possibleDivisor (1) except for 1. Hence you only get 1.