3 Replies Latest reply: Mar 27, 2013 5:08 PM by 999443 RSS

    Trouble Understanding Logic of Primes Program

    999443
      I am reading a book called Beginning Java 7, by Ivor Horton. In his book he has a primes calculation program. The code is below. I am having trouble understanding the logic of the program. I've stared at it for the past several hours with no luck. What I can't understand is how both i and j are both initialized to 2 but the if statement:
      if(i%j == 0) {
                continue OuterLoop;                                          
              }
      then passes a 2 to the println() function. I am totally lost on this problem. The program below outputs all of the prime numbers from 2 to 50 without any errors. Please help!
      Thank you.
      public class Primes2 {
        public static void main(String[] args) {
          int nValues = 50;                                                  // The maximum value to be checked
      
          // Check all values from 2 to nValues
          OuterLoop:
          for(int i = 2 ; i <= nValues ; ++i) {
            // Try dividing by all integers from 2 to i-1
            for(int j = 2 ;  j < i ; ++j) {
              if(i%j == 0) {                                                 // This is true if j divides exactly
                continue OuterLoop;                                          // so exit the loop
              }
            }
            // We only get here if we have a prime
            System.out.println(i);                                           // so output the value
          }
        }
      }
      Edited by: EJP on 27/03/2013 19:54: fixed all the bizarre formatting, spelling, and removed the even more bizarre comment marketers around the text. Please use standard English and its existing conventions here.