Advertisement
konstantin_mechev

Untitled

Jan 9th, 2013
266
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.44 KB | None | 0 0
  1. // Write a program that finds all prime numbers in the range [1...10 000 000].
  2. // Use the sieve of Eratosthenes algorithm (find it in Wikipedia).
  3.  
  4. using System;
  5.  
  6. class primeNumbers
  7. {
  8.     static void Main(string[] args)
  9.     {
  10.         int[] arr = new int[5000001];
  11.         arr[0] = 0;
  12.         for (int i = 1, j = 1; i < 5000001; i++, j+= 2) // Записваме в масива само нечетни числа
  13.         {
  14.             arr[i] = j;
  15.         }
  16.         Console.Write(arr[1] + " ");
  17.         for (int i = 2; i <= 1582; i++) // Проверяваме до корен квадратен от 10 000 000 => 1582 е                     позицията на необходимото ни число (3163)
  18.         {
  19.             if (arr[i] != 0)            // Същевременно печатаме получените прости числа до корена                     квадратен от 10 000 000
  20.             {
  21.                 for (int j = i + 1; j < 5000001; j++)
  22.                 {
  23.                     if (arr[j] % arr[i] == 0)
  24.                     {
  25.                         arr[j] = 0;
  26.                     }
  27.                 }
  28.                 Console.Write(arr[i] + " ");
  29.             }
  30.         }
  31.         for (int i = 1582; i < 5000001; i++) // Печатаме останалите прости числа
  32.         {
  33.             if (arr[i] != 0)
  34.             {
  35.                 Console.Write(arr[i] + " ");
  36.             }
  37.         }
  38.     }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement