Advertisement
sylviapsh

Sieve Of Eratosthenes For Prime Nums

Jan 11th, 2013
33
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.61 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. class SieveOfEratosthenesForPrimeNums
  6. {
  7.   static void Main()
  8.   {
  9.     //Write a program that finds all prime numbers in the range [1...10 000 000]. Use the sieve of Eratosthenes algorithm (find it in Wikipedia).
  10.  
  11.     int[] numbersArray = new int[10000001];
  12.     List<int> primeNumbers = new List<int>();
  13.  
  14.     //Fill the numbersArray with all the numbers in the interval [0, 10000000] - starts from zero so that the index matches
  15.     for (int i = 0; i <= 10000000; i++)
  16.     {
  17.       numbersArray[i] = i;
  18.     }
  19.  
  20.     int upperLimit = (int)Math.Sqrt(numbersArray.Length); //Get the sqrt of the lenght of the array so that we could use it as an upper limit to find the prime nums
  21.  
  22.     for (int i = 2; i <= upperLimit; i++) //Start with  the number 2 to do the Eratosthenes algorithm
  23.     {
  24.       if (numbersArray[i] != 0) //If the element in that position is not 0 we could remove the numbers that are not prime that can be divided to it
  25.       {
  26.  
  27.        for (int j = 2 * i; j < numbersArray.Length; j += i) // do the Eratosthenes algorithm for each number. Make 0 each element that should be removed
  28.         {
  29.           numbersArray[j] = 0;
  30.         }
  31.       }
  32.     }
  33.  
  34.  
  35.     for (int i = 0; i < numbersArray.Length; i++) //Output all prime numbers in a list
  36.     {
  37.       if (numbersArray[i] != 0)
  38.       {
  39.         primeNumbers.Add(numbersArray[i]);
  40.       }
  41.     }
  42.  
  43.     //Print the numbers on the console. NOTE! It takes quite a time!
  44.     for (int i = 0; i < primeNumbers.Count; i++)
  45.     {
  46.       Console.WriteLine(primeNumbers[i]);
  47.     }
  48.   }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement