New in sets: How to implement the sieve of Eratosthenes in java











up vote
1
down vote

favorite












I am new to sets and I found this problem in a book:



Implement the sieve of Eratosthenes: a method for computing prime numbers, known to the ancient Greeks. Choose an n. This method will compute all prime numbers up to n. First insert all numbers from 2 to n into a set. Then erase all multiples of 2 (except 2); that is, 4, 6, 8, 10, 12, …. Erase all multiples of 3; that is, 6, 9, 12, 15, …. Go up to . Then print the set.



I have written this code:



import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

public class SieveOfEratosthenes {
public static void main (String args){
System.out.print(generatePrime(20));
}

public static Set generatePrime(int n){
Set<Integer> primes = new TreeSet<>();
Iterator<Integer> iter = primes.iterator();

//generate all numbers up to n and add them to the set
for (int i = 2; i < n; i++){
primes.add(i);
}

//for numbers up to root n
for (int f = 2; f <= Math.sqrt(n); f++){
while (iter.hasNext()){
int current = iter.next();
if (current % f == 0 && current != 2){
primes.remove(current);

}
}

}

return primes;
}
}


The problem is that the code in the while loop doesn't implement. When I debugged the program I found that hasNext() is returning null. I couldn't figure out the reason of doing so although the list contains the numbers.



This is the output that I get from the code:



[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
Process finished with exit code 0


Thank you in advance!










share|improve this question


























    up vote
    1
    down vote

    favorite












    I am new to sets and I found this problem in a book:



    Implement the sieve of Eratosthenes: a method for computing prime numbers, known to the ancient Greeks. Choose an n. This method will compute all prime numbers up to n. First insert all numbers from 2 to n into a set. Then erase all multiples of 2 (except 2); that is, 4, 6, 8, 10, 12, …. Erase all multiples of 3; that is, 6, 9, 12, 15, …. Go up to . Then print the set.



    I have written this code:



    import java.util.Iterator;
    import java.util.Set;
    import java.util.TreeSet;

    public class SieveOfEratosthenes {
    public static void main (String args){
    System.out.print(generatePrime(20));
    }

    public static Set generatePrime(int n){
    Set<Integer> primes = new TreeSet<>();
    Iterator<Integer> iter = primes.iterator();

    //generate all numbers up to n and add them to the set
    for (int i = 2; i < n; i++){
    primes.add(i);
    }

    //for numbers up to root n
    for (int f = 2; f <= Math.sqrt(n); f++){
    while (iter.hasNext()){
    int current = iter.next();
    if (current % f == 0 && current != 2){
    primes.remove(current);

    }
    }

    }

    return primes;
    }
    }


    The problem is that the code in the while loop doesn't implement. When I debugged the program I found that hasNext() is returning null. I couldn't figure out the reason of doing so although the list contains the numbers.



    This is the output that I get from the code:



    [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
    Process finished with exit code 0


    Thank you in advance!










    share|improve this question
























      up vote
      1
      down vote

      favorite









      up vote
      1
      down vote

      favorite











      I am new to sets and I found this problem in a book:



      Implement the sieve of Eratosthenes: a method for computing prime numbers, known to the ancient Greeks. Choose an n. This method will compute all prime numbers up to n. First insert all numbers from 2 to n into a set. Then erase all multiples of 2 (except 2); that is, 4, 6, 8, 10, 12, …. Erase all multiples of 3; that is, 6, 9, 12, 15, …. Go up to . Then print the set.



      I have written this code:



      import java.util.Iterator;
      import java.util.Set;
      import java.util.TreeSet;

      public class SieveOfEratosthenes {
      public static void main (String args){
      System.out.print(generatePrime(20));
      }

      public static Set generatePrime(int n){
      Set<Integer> primes = new TreeSet<>();
      Iterator<Integer> iter = primes.iterator();

      //generate all numbers up to n and add them to the set
      for (int i = 2; i < n; i++){
      primes.add(i);
      }

      //for numbers up to root n
      for (int f = 2; f <= Math.sqrt(n); f++){
      while (iter.hasNext()){
      int current = iter.next();
      if (current % f == 0 && current != 2){
      primes.remove(current);

      }
      }

      }

      return primes;
      }
      }


      The problem is that the code in the while loop doesn't implement. When I debugged the program I found that hasNext() is returning null. I couldn't figure out the reason of doing so although the list contains the numbers.



      This is the output that I get from the code:



      [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
      Process finished with exit code 0


      Thank you in advance!










      share|improve this question













      I am new to sets and I found this problem in a book:



      Implement the sieve of Eratosthenes: a method for computing prime numbers, known to the ancient Greeks. Choose an n. This method will compute all prime numbers up to n. First insert all numbers from 2 to n into a set. Then erase all multiples of 2 (except 2); that is, 4, 6, 8, 10, 12, …. Erase all multiples of 3; that is, 6, 9, 12, 15, …. Go up to . Then print the set.



      I have written this code:



      import java.util.Iterator;
      import java.util.Set;
      import java.util.TreeSet;

      public class SieveOfEratosthenes {
      public static void main (String args){
      System.out.print(generatePrime(20));
      }

      public static Set generatePrime(int n){
      Set<Integer> primes = new TreeSet<>();
      Iterator<Integer> iter = primes.iterator();

      //generate all numbers up to n and add them to the set
      for (int i = 2; i < n; i++){
      primes.add(i);
      }

      //for numbers up to root n
      for (int f = 2; f <= Math.sqrt(n); f++){
      while (iter.hasNext()){
      int current = iter.next();
      if (current % f == 0 && current != 2){
      primes.remove(current);

      }
      }

      }

      return primes;
      }
      }


      The problem is that the code in the while loop doesn't implement. When I debugged the program I found that hasNext() is returning null. I couldn't figure out the reason of doing so although the list contains the numbers.



      This is the output that I get from the code:



      [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
      Process finished with exit code 0


      Thank you in advance!







      java while-loop iterator set






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 11 at 16:34









      Noussa

      63




      63
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          0
          down vote



          accepted










          You're creating the Iterator before you add elements to the Set when you should be creating it after (inside the for-loop):



          Set<Integer> primes = new TreeSet<>();

          //generate all numbers up to n and add them to the set
          for (int i = 2; i < n; i++) {
          primes.add(i);
          }

          //for numbers up to root n
          for (int f = 2; f <= Math.sqrt(n); f++){
          Iterator<Integer> iter = primes.iterator();


          Also, I recommend changing the following:



          primes.remove(current);


          To:



          iter.remove();


          To avoid any ConcurrentModificationExceptions.





          Lastly, it seems you still have an issue where 3 is not in the resulting Set, which you'll have to debug.






          share|improve this answer

















          • 1




            Thank you for your help! I could find the problem for the number 3
            – Noussa
            Nov 11 at 18:12













          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53250827%2fnew-in-sets-how-to-implement-the-sieve-of-eratosthenes-in-java%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          0
          down vote



          accepted










          You're creating the Iterator before you add elements to the Set when you should be creating it after (inside the for-loop):



          Set<Integer> primes = new TreeSet<>();

          //generate all numbers up to n and add them to the set
          for (int i = 2; i < n; i++) {
          primes.add(i);
          }

          //for numbers up to root n
          for (int f = 2; f <= Math.sqrt(n); f++){
          Iterator<Integer> iter = primes.iterator();


          Also, I recommend changing the following:



          primes.remove(current);


          To:



          iter.remove();


          To avoid any ConcurrentModificationExceptions.





          Lastly, it seems you still have an issue where 3 is not in the resulting Set, which you'll have to debug.






          share|improve this answer

















          • 1




            Thank you for your help! I could find the problem for the number 3
            – Noussa
            Nov 11 at 18:12

















          up vote
          0
          down vote



          accepted










          You're creating the Iterator before you add elements to the Set when you should be creating it after (inside the for-loop):



          Set<Integer> primes = new TreeSet<>();

          //generate all numbers up to n and add them to the set
          for (int i = 2; i < n; i++) {
          primes.add(i);
          }

          //for numbers up to root n
          for (int f = 2; f <= Math.sqrt(n); f++){
          Iterator<Integer> iter = primes.iterator();


          Also, I recommend changing the following:



          primes.remove(current);


          To:



          iter.remove();


          To avoid any ConcurrentModificationExceptions.





          Lastly, it seems you still have an issue where 3 is not in the resulting Set, which you'll have to debug.






          share|improve this answer

















          • 1




            Thank you for your help! I could find the problem for the number 3
            – Noussa
            Nov 11 at 18:12















          up vote
          0
          down vote



          accepted







          up vote
          0
          down vote



          accepted






          You're creating the Iterator before you add elements to the Set when you should be creating it after (inside the for-loop):



          Set<Integer> primes = new TreeSet<>();

          //generate all numbers up to n and add them to the set
          for (int i = 2; i < n; i++) {
          primes.add(i);
          }

          //for numbers up to root n
          for (int f = 2; f <= Math.sqrt(n); f++){
          Iterator<Integer> iter = primes.iterator();


          Also, I recommend changing the following:



          primes.remove(current);


          To:



          iter.remove();


          To avoid any ConcurrentModificationExceptions.





          Lastly, it seems you still have an issue where 3 is not in the resulting Set, which you'll have to debug.






          share|improve this answer












          You're creating the Iterator before you add elements to the Set when you should be creating it after (inside the for-loop):



          Set<Integer> primes = new TreeSet<>();

          //generate all numbers up to n and add them to the set
          for (int i = 2; i < n; i++) {
          primes.add(i);
          }

          //for numbers up to root n
          for (int f = 2; f <= Math.sqrt(n); f++){
          Iterator<Integer> iter = primes.iterator();


          Also, I recommend changing the following:



          primes.remove(current);


          To:



          iter.remove();


          To avoid any ConcurrentModificationExceptions.





          Lastly, it seems you still have an issue where 3 is not in the resulting Set, which you'll have to debug.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 11 at 16:40









          Jacob G.

          14.9k51962




          14.9k51962








          • 1




            Thank you for your help! I could find the problem for the number 3
            – Noussa
            Nov 11 at 18:12
















          • 1




            Thank you for your help! I could find the problem for the number 3
            – Noussa
            Nov 11 at 18:12










          1




          1




          Thank you for your help! I could find the problem for the number 3
          – Noussa
          Nov 11 at 18:12






          Thank you for your help! I could find the problem for the number 3
          – Noussa
          Nov 11 at 18:12




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53250827%2fnew-in-sets-how-to-implement-the-sieve-of-eratosthenes-in-java%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Bressuire

          Vorschmack

          Quarantine