Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- class SieveOfEratosthenesForPrimeNums
- {
- static void Main()
- {
- //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).
- int[] numbersArray = new int[10000001];
- List<int> primeNumbers = new List<int>();
- //Fill the numbersArray with all the numbers in the interval [0, 10000000] - starts from zero so that the index matches
- for (int i = 0; i <= 10000000; i++)
- {
- numbersArray[i] = i;
- }
- 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
- for (int i = 2; i <= upperLimit; i++) //Start with the number 2 to do the Eratosthenes algorithm
- {
- 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
- {
- 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
- {
- numbersArray[j] = 0;
- }
- }
- }
- for (int i = 0; i < numbersArray.Length; i++) //Output all prime numbers in a list
- {
- if (numbersArray[i] != 0)
- {
- primeNumbers.Add(numbersArray[i]);
- }
- }
- //Print the numbers on the console. NOTE! It takes quite a time!
- for (int i = 0; i < primeNumbers.Count; i++)
- {
- Console.WriteLine(primeNumbers[i]);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement