I do not understand the logic behind this number checker and I'm wondering if somebody could help me understand it a little bit better.
Here's the code:
I will do my best to comment on what's happening but I do not fully understand it.
//find prime numbers between 2 and 100
class PrimeNumberFinder {
public static void main(String args[]) {
int i, j; // declare the integer variables "i" and "j"
boolean isPrime; // declare the Boolean variable is prime but do not assign value
// create a for loop that starts at two and stops at 99.
for (i=2; i < 100 ; i++) {
isPrime = true; // I do not know why isPrime is set to true here.
// This is where I get confused badly.. we give the "j" variable a value of two and check to see if it's less than whatever "i" divided by "j" is.
// If "i=2" then how would j (which is = 2) be less than or equal to i/j (2/2)?
for (j = 2; j <= i/j; j++)
if ((i%j) == 0) isPrime = false; // If a certain number goes in evenly that isn't 1, or "i" itself, it isn't prime so we set the boolean to false
if (isPrime) // if true print i
System.out.println(i + " Is a prime number");
}
}
}
As you can see the second for loop and almost everything going on within it confuses me, especially the "j <= i/j" because to me j is always going to be bigger.. and why is "j" even increasing? Can't you just divide it by two and determine whether or not it's prime that way?
Any help is greatly appreciated, thank you for reading.
Aucun commentaire:
Enregistrer un commentaire