0

Summary: Attempting to learn alternative ways of doing things. The part of Java that I understand least is how each piece of code communicates with one another. As such, instead of using a method call in the classic isPrime for loop generation, I'm attempting to do so with using nested loops only. However, the closest I have gotten is to have it increment by 2 up to 100 -- it isn't checking for if it's prime. I have provided sample code, but I'm not sure why my code does not work as intended. If possible, please correct my code sample and explain your correction(s).

What I'm trying to do: add all prime numbers 2-->100 into set A (2 has been added before beginning)

Expected: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31... Actual: ...5,7,9,11,13,15,17... (+=2 all the way to 99)

Why does this code only count by 2, instead of using the condition I have specified?

My logic is:

  1. prepare everything (create stuff, add 2 to set)
  2. condition addNumber -- if true, add that to the set, if not, move on to next number
  3. outer loop -- n -- is the number being tested. start at 3, increment by 2s (no even numbers will be prime), up to 100
  4. inner loop -- i -- "i --> n" range is used for checking if prime. if n is divisible by i, the number is NOT prime
  5. if the number was not found to violate n%i==0, add it to the vector
  6. if it was found to violate the condition, exit inner loop and move onto the next number

I don't understand why break; isn't working as I intend. I don't understand why, even if break somehow won't work, me specifying the termination condition doesn't work. I don't understand why it seems like my check is never being reached and it's just adding every 2 numbers...

Things I've tried: played around with break and terminations. Moved things inside and outside of portions of the nested loops.

All I can get to have happen is for it to count by 2, or for it to add up to 7 and then stop at the first value it shouldn't add (9)

Research I've done:

Breaking out of nested loops in Java

Why do we check up to the square root of a prime number to determine if it is prime?

Prime Number Generator Logic

The ideal answer would be sample code with a correction of my code and an explanation. I am trying to do this WITHOUT using an isPrime method, the logic for that method must be inside the loop that adds the number.

public static void main(String[] args) {
     boolean addNumber = true; 
     for (int n = 3; n < 100; n = n+2) { //outer loop -- argument
         for(int i=2; i< n; i++){ //check if 2-->n is a divisor
             if (n % i == 0){ //if it's NOT prime 
                 addNumber = false; //set condition to FALSE
                 i=n+1; //ensure that inner loop break condition is met
                 break; //literally tell it to break
             }
             else {
                 i=n+1;
                 break; //if the above is not met, ensure that the inner loop is broken
             }

         }//closes inner loop

         //before exiting loop, add the confirmed prime number to set
         if(addNumber) //if we should add it
             A.append(n); //add it 
     }//closes outer loop

     System.out.println(A);
}

EDIT: It turns out using "break;" here is only a matter of efficiency. As soon as we determine that n is not a prime number, why continue running through all the remaining i values? I've continued playing around with this topic, and have come up with a scenario in which using break is actually necessary.

Consider: instead of wanting to add prime numbers between 2 and 100 to the set, let’s say we want to add the first 25 prime numbers to the set.

We need to change the outer loop to something “safe” (not exactly proper, but just for this example) let’s say n = 1000. This way, we know that we won’t run out of prime numbers to be added; there are definitely 25 prime numbers between 2 and 1000.

for (int n = 3; n < 1000; n++) {
  addNumber = true;
  ....

NOW we actually need to use break! Before terminating the outer loop in the correct code sample below (by @Nani2015), we need to add:

if(A.size() == 25 )
  break; //break out of outer loop -- we have the desired number of elements

This checks whether or not the set we are working with, A, has the amount of elements we desire. If FALSE: do nothing. If TRUE: break (we are done)

Hopefully this clarifies things. In my original question, using break was entirely unnecessary. All I needed to do was remove both breaks, and my code would have worked as intended. However, inputting breaks in incorrect areas caused issues. "break;" should be used when you wish to or need to terminate the loop prior to its termination condition being met.

Community
  • 1
  • 1
coder
  • 25
  • 6
  • No matter which condition is met, you break out of the inner loop - thus you don't actually iterate from i to n... – MordechayS Oct 16 '16 at 03:17
  • Thank you for pointing that out. I had tried putting the second "break;" in several different locations, but to no avail. Your comment is 100% correct, but it turns out my actual issue was having two breaks in general. Not to mention, break seems to only have been a matter of efficiency here.The accepted answer also addressed some improvements in efficiency that could be made. Also, thank you @BrainFRZ for assisting me with formatting the question. Could I have initiated that process myself? And is my rep the reason why I cannot edit my comments (see my comment replies to the accepted answer)? – coder Oct 16 '16 at 05:46
  • Another assignment question? As I said before, you won't learn anything, and you are using this resource incorrectly. You said you are afraid to ask the teacher, you shouldn't be--they are there to help you. – wellplayed Oct 24 '16 at 14:04

1 Answers1

1

I recommend using an IDE like Eclipse, it shows if there is any the dead code. In your case, inner loop's i++ is dead code as you are doing i=n+1. i is always greater than n after first iteration. Use the following code as reference

public static void main(String[] args) {
    HashSet<Integer> A = new HashSet<>();
    A.add(2);
    boolean addNumber;
    for (int n = 3; n < 100; n++) {
        addNumber = true;
        for (int i = 2; i <= n / 2; i++) {
            if (n % i == 0) {
                addNumber = false;
                break;
            }
        }
        if (addNumber)
            A.add(n);
    }
    System.out.println(A);
}
  • Thank you! This is exactly what I was looking for, and makes perfect sense. Seeing code and thinking it through always seems to be more effective for me, as opposed to reading paragraphs about logic; such as, "the break command does ___". – coder Oct 16 '16 at 05:14
  • (For some reason, I could not edit my previous comment within a 5 minute window. I didn’t see an edit button or a pencil icon or anything (?) Sorry for the double post here.) – coder Oct 16 '16 at 05:24
  • ^ did it again...can a moderator please remedy this? Anyway, I've been trying to say: I've marked your answer as accepted and upvoted it. Thank you for your quick, easy to understand reply! – coder Oct 16 '16 at 05:25
  • Please don't ask or answer homework questions. You will never learn this way, and besides, it condescending. – wellplayed Oct 24 '16 at 14:03