Created
February 4, 2023 16:52
-
-
Save EgorBron/36632915a379b87eb74cb32abf5d123f to your computer and use it in GitHub Desktop.
Implementation of the "Sieve of Eratosthenes" algorithm for generating prime numbers up to N in C#
This file contains hidden or 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
/// <summary> | |
/// Implementation of the "Sieve of Eratosthenes" algorithm for generating prime numbers up to N in C# | |
/// </summary> | |
public static class SieveOfEratosthenes { | |
/// <summary> | |
/// Checking for a prime number with <see cref="Sieve(int)"/> | |
/// </summary> | |
/// <param name="num">Number to check</param> | |
/// <returns>Is <paramref name="num"/> prime number or not</returns> | |
public static bool IsPrimeNumber(int num) => Sieve(num).Contains(num); | |
/// <summary> | |
/// Generates an array of prime numbers up to <paramref name="generateTo"/> | |
/// </summary> | |
/// <param name="generateTo">Array limit</param> | |
/// <returns>An array of prime integers</returns> | |
public static int[] Sieve(int generateTo) { | |
List<int> output = new(); | |
bool[] checks = new bool[++generateTo]; | |
Array.Fill(checks, true); | |
checks[0] = checks[1] = false; | |
for (int i = 0; i < checks.Length; i++) { | |
if (!checks[i]) continue; | |
for (int j = 2; j <= checks.Length; j++) { | |
if (i * j >= checks.Length) break; | |
checks[i * j] = false; | |
} | |
} | |
for (int i = 0; i < checks.Length; i++) if (checks[i]) output.Add(i); | |
return output.ToArray(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment