Advertisement
soxa

Eratosthenes algorithm

Dec 18th, 2013
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.73 KB | None | 0 0
  1. using System;
  2. //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).
  3.  
  4. class FindsAllPrime
  5. {
  6.     static void Main()
  7.     {
  8.         //Input
  9.         int n = 10000000;
  10.         int[] array = new int[n];
  11.         array[0] = 1;
  12.         array[1] = 1;
  13.         array[2] = 0;
  14.  
  15.         //Solution
  16.         for (int i = 2; i < Math.Sqrt(n); i++)
  17.         {
  18.             for (int j = 2; j*i < n; j++)
  19.             {
  20.                 array[j*i] = 1;
  21.             }
  22.         }
  23.  
  24.     //Output
  25.         for (int i = 0; i < n; i++)
  26.         {
  27.             if (array[i] == 0)
  28.             {
  29.                 Console.WriteLine(i);
  30.             }
  31.         }
  32.     }
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement