Advertisement
Klaxon

[C# Arrays] Sieve of Eratosthenes Algorithm

Sep 30th, 2013
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.86 KB | None | 0 0
  1. // 15. 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).
  2.  
  3. using System;
  4.  
  5. class SieveOfEratosthenesAlgorithm
  6. {
  7.     static void Main()
  8.     {
  9.         // all numbers to check
  10.         bool[] isPrime = new bool[10000000];
  11.  
  12.         // main magic
  13.         for (int i = 2; i < Math.Sqrt(isPrime.Length); i++)
  14.         {
  15.             if (isPrime[i] == false)
  16.             {
  17.                 for (int j = i * i; j < isPrime.Length; j = j + i)
  18.                 {
  19.                     isPrime[j] = true;
  20.                 }
  21.             }
  22.         }
  23.  
  24.         // printing
  25.         for (int i = 2; i < isPrime.Length; i++)
  26.         {
  27.             if (isPrime[i] == false)
  28.             {
  29.                 Console.Write("{0} ", i);
  30.             }
  31.         }
  32.         Console.WriteLine();
  33.     }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement