Skip to content

Instantly share code, notes, and snippets.

@davidsekar
Last active June 25, 2023 19:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save davidsekar/6fcf8ec134c5209b6dea to your computer and use it in GitHub Desktop.
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)
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