Unsure of how code works: Example: Primes
/**I've left the programmers comments in. What I am having trouble with is
the part of the code that reads (below this comment block):
If(i % j == 0) {
isPrime = false;
break;
}
What I am having trouble with is that both i and j are the same value incremented each time they run...I think...so wouldn't that mean that the value of i % j would always be zero because it is the same value divided by another? What am I missing? And then also, if there is no remainder wouldn't that indicate that the number is prime? I know there is something I am missing...Please help me out. Thank you. :)
*/
public class Primes {
public static void main(String[] args) {
int nValues = 50; // The maximum value to be checked
boolean isPrime = true; // Is true if we find a prime
// Check all values from 2 to nValues
for(int i = 2; i <= nValues; ++i) {
isPrime=true; // Assume the current i is prime
// Try dividing by all integers from 2 to i1
for(int j = 2; j < i; ++j) {
if(i % j == 0) { // This is true if j divides exactly
isPrime = false; // If we got here, it was an exact division
break; // so exit the loop
}
}
// We can get here through the break, or through completing the loop
if(isPrime) // So is it prime?
System.out.println(i); // Yes, so output the value
}
}
}
/**
The outputs in the book are:
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
*/
Last edited by alex001; March 26th, 2013 at 04:36 AM.
