You made some silly little mistakes.
Your big mistake is that you don’t do the counter
go back to zero after iterating a number on i
. Because of this, after deciding that 1 is not prime, he will never be able to decide which number is prime, since counter
never diminishes.
Another small problem was the stopping condition of the for
that was 1 <= 100
instead of i <= 100
.
Finally, you can declare the variables i
and k
within itself for
, don’t need to declare first.
One more space to add before the "is prime"
.
So, here’s 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");
}
}
}
}
It’s also possible to optimize your code a little bit more, because you don’t have to ever 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, because as soon as you find a divisor you already know that the number is composed and you do not need to waste time testing the other numbers, being able to use the continue
to proceed to the next iteration. This also eliminates the need for the variable counter
. 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 optimize further if you check that if the number is composed, then at least one of the divisors is less than or equal to square root of the number. So if you even get to the square root, you don’t find any divisor, it’s because the number is prime. Soon:
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, in particular to avoid testing k
which are compounds and also to compute the whole square root which is faster than the square floating point root. Other properties of primes and compounds 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, especially since you’re only testing the primes up to the number 100.
Just remembering that a cousin only divides by himself and one, so the counter == 2
– user35460
Try to put ++ on the right side of the contain variable
– Emir Marques
Need to reset to counter variable after if(counter == 2)
– bruno