You made some silly little mistakes.
-
Your big mistake is that you do not make counter
back to zero after iterating a number in i
. Because of this, after deciding that 1 is not prime, it will never be able to decide that any number is prime, since counter
never decreases.
-
Another problem was the stopping condition of for
that was 1 <= 100
instead of i <= 100
.
-
Finally, you can declare the variables i
and k
within the for
itself, you do not need to declare before.
-
Failed to add a space before "is prime"
.
So here is your corrected code.
public class Main {
public static void main(String args[]) {
for (int i = 1; i <= 100; i++) {
int counter = 0;
for (int k = 1; k <= i; k++) {
if (i % k == 0) ++counter;
}
if (counter == 2) {
System.out.println("The number: " + i + " is prime");
}
}
}
}
You can also optimize your code a bit more because you never need to test whether the number is divisible by 1 or by itself, because it always will be. This way, you no longer need to count the divisors, as soon as you find a divisor you already know that the number is composed and you do not have to waste time testing the other numbers, you can use continue
to move on to the next iteration. This also eliminates the need for the counter
variable. This way, your code looks like this:
public class Main {
public static void main(String args[]) {
out: for (int i = 1; i <= 100; i++) {
for (int k = 2; k < i; k++) {
if (i % k == 0) continue out;
}
System.out.println("The number: " + i + " is prime");
}
}
}
You can further optimize if you verify that if the number is composed, then at least one of the divisors is less than or equal to the square root of the number. So, if until you get to the square root, you find no divisor, it's because the number is prime. Logo:
public class Main {
public static void main(String args[]) {
out: for (int i = 1; i <= 100; i++) {
for (int k = 2; k <= Math.sqrt(i); k++) {
if (i % k == 0) continue out;
}
System.out.println("The number: " + i + " is prime");
}
}
}
There are other possible mathematical tricks, especially to avoid testing values of k
that are composed and also to compute the entire square root that is faster than the square root of floating point. Other properties of prime numbers and composites can be used to reduce computational effort. However, these more aggressive optimizations would no longer be simple, and you probably want an algorithm that is quite simple, even more so that you are only testing cousins up to number 100.