Last active
June 25, 2023 19:24
-
-
Save davidsekar/6fcf8ec134c5209b6dea to your computer and use it in GitHub Desktop.
C# - Program to find all primes upto a given number (Seive of Eratosthenes)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
Console.WriteLine("Enter the number upto which you want to list primes"); | |
int n = Convert.ToInt32(Console.ReadLine()); | |
bool[] prime = new bool[n + 1]; // default value is false for boolean | |
for (int i = 2; i <= n; i++) prime[i] = true; | |
int limit = (int)Math.Ceiling(Math.Sqrt(n)); | |
for (int i = 2; i <= limit; i++) | |
if (prime[i]) | |
for (int j = i * i; j <= n; j += i) | |
prime[j] = false; | |
Console.WriteLine("Prime Numbers upto {0}", n); | |
for (int i = 0; i <= n; i++) | |
if (prime[i]) | |
Console.WriteLine(i); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment