I want to print all prime numbers that are 2-digits long. Here is my code:
for(int input = 11; input <= 99; input += 2){
for(int x = 2; x < (int)Math.sqrt(input) + 1; x++){
if(input%x != 0){
System.out.println(input);
break;
}else{
break;
}
}
}
The problem is that it prints numbers like 35 or 49 which are not prime numbers.
Your test for primeness is incorrect. You stop testing a number (input
) as soon as you find a divisor which the input
is not divisible by.
That's not the definition of prime - you need to test that the input
number is not divisible by any divisors less than it - in other words you need to test all values of x
before you can declare a number as prime.
You can break out of the loop that checks input % x != 0
when an input
is divisible by x
, but not when it is not divisible - you need to keep on checking when this condition is true!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With