Advertisement
Hristo_B

SieveOfEratosthenes

Jun 10th, 2013
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.51 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. class SieveOfEratosthenes
  5. {
  6.     static void Main()
  7.     {
  8.         //Write a program that finds all prime numbers in the range [1...10 000 000].
  9.         //Use the sieve of Eratosthenes algorithm (find it in Wikipedia).
  10.  
  11.         List<int> numbers = new List<int>();
  12.  
  13.         const int max = 10000000;
  14.  
  15.         for (int i = 1; i <= max; i++)
  16.         {
  17.             numbers.Add(i); // adds this 10 000 000 in the list
  18.         }
  19.  
  20.         int counter = 2;
  21.         int CurrentNumber = 2;
  22.  
  23.         while ((CurrentNumber*CurrentNumber) < max) // we have to check the numbers until the current number is smaller than the biggest number
  24.         {
  25.             while ((counter * CurrentNumber) <= max)// checks if we have reached the biggest number
  26.             {
  27.                 numbers[(counter * CurrentNumber) - 1] = 0; // makes the current number 0 if it is not prime
  28.                 counter++;
  29.             }
  30.             if (numbers[CurrentNumber] == 0 ) // this makes sure we don't try with numbers like 4, 6, 8 ... which we have already crossed
  31.             {
  32.                 CurrentNumber += 2;
  33.             }
  34.             else
  35.             {
  36.                 CurrentNumber++;
  37.             }
  38.            
  39.             counter = 2;
  40.         }
  41.  
  42.         for (int i = 1; i < numbers.Count; i++)
  43.         {
  44.             if (numbers[i] != 0)
  45.             {
  46.                 Console.Write(numbers[i] + " "); // prints the prime numbers
  47.             }
  48.         }
  49.  
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement