Reputation: 101
So I am trying to figure out how to make a prime number program, now I know how to verify a prime number, so i tried to freestyle it, but it seems like programming it requires more restrictions than usual to create prime numbers up to a 100. I tried many ways and followed many methods, many of them seem complex. But this program here seems very easy to understand, but i still have trouble understanding the boolean variable purpose?
public static void main(String[] args) {
for (int i = 2; i <=100; i ++) {
boolean primeNum = true;
for (int j = 2; j <i; j++) {
if (i%j == 0) {
primeNum = false;
break;
}
}
if (primeNum) {
System.out.println(i);
}
}
}
Upvotes: 0
Views: 68
Reputation: 643
What it does is make a mod to every number less than the current one. If the modular is 0, then the current number can be divided, hence it is not a prime number.
The boolean
flag is changed whenever a number can be divided by a number different than 1 and itself. If the flag is true
, then no division happens and it is a prime number and be printed out, otherwise, nothing is printed.
Upvotes: 1
Reputation: 193
Looks like the purpose of primeNum is to "save" whether or not it's a prime, then print it out. We only know whether it's a prime after we've gone through all the divisors (index of j)
Upvotes: 0