title: C# Sieve of Eratosthenes
body: <p>I have written this code to find prime numbers, and it works well, but the calculation speeds are incredibly slow..... Am I doing this wrong? I know that I might be really doing this the wrong way, but please help me! Thank you very much!</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  
  namespace Primenumbers
  {
      class MainClass
      {
          public static void Main (string[] args)
          {    
              List&lt;int&gt; NoPrime = new List&lt;int&gt;();
  
              for(int x = 2; x &lt; 10000;x++)
              {
                  for(int y = x * 2;y &lt; 10000;y = y + x)
                  {    
                      if(!NoPrime.Contains(y))
                      {
                          NoPrime.Add(y);
                      }    
                  }    
              }
  
              for(int z = 2; z &lt; 10000;z++)
              {
                  if(!NoPrime.Contains(z))
                  {
                      Console.WriteLine(z);
                  }
              }
          }
      }
  }
  </code></pre>
  
  <p><strong>EDIT:</strong>
  This is the new code, I changed 'List' to 'HashSet' and added a counter to get the sum of all the prime numbers. A big thank you to everyone who commented/answered, you guys are awesome!</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  
  class MainClass
  {
      public static void Main (string[] args)
      {
          HashSet&lt;int&gt; NoPrime = new HashSet&lt;int&gt;();
  
          long count = 0;
          int n = 2000000;
  
          for(int x = 2; x &lt; n;x++)
          {
              for(int y = x * 2;y &lt; n;y = y + x)
              {
  
              if(!NoPrime.Contains(y))
              {
                  NoPrime.Add(y);
              }
          }
  
          for(int z = 2; z &lt; n;z++)
          {
              if(!NoPrime.Contains(z))
              {
                  Console.WriteLine(z);
                  count = count + z;
              }
          }
  
          Console.WriteLine("Sum is: " + count);
      }
  }
  </code></pre>