forked from TheAlgorithms/C-Sharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SieveOfEratosthenes.cs
67 lines (58 loc) · 2.08 KB
/
SieveOfEratosthenes.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
using System;
using System.Collections.Generic;
namespace Algorithms.Other;
/// <summary>
/// Implements the Sieve of Eratosthenes.
/// </summary>
public class SieveOfEratosthenes
{
private readonly bool[] primes;
/// <summary>
/// Initializes a new instance of the <see cref="SieveOfEratosthenes"/> class.
/// Uses the Sieve of Eratosthenes to precalculate the primes from 0 up to maximumNumberToCheck.
/// Requires enough memory to allocate maximumNumberToCheck bytes.
/// https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes .
/// </summary>
/// <param name="maximumNumberToCheck">long which specifies the largest number you wish to know if it is prime.</param>
public SieveOfEratosthenes(long maximumNumberToCheck)
{
primes = new bool[maximumNumberToCheck + 1];
// initialize primes array
Array.Fill(this.primes, true, 2, primes.Length - 2);
for(long i = 2; i * i <= maximumNumberToCheck; i++)
{
if (!primes[i])
{
continue;
}
for(long composite = i * i; composite <= maximumNumberToCheck; composite += i)
{
primes[composite] = false;
}
}
}
/// <summary>
/// Gets the maximumNumberToCheck the class was instantiated with.
/// </summary>
public long MaximumNumber => primes.Length - 1;
/// <summary>
/// Returns a boolean indicating whether the number is prime.
/// </summary>
/// <param name="numberToCheck">The number you desire to know if it is prime or not.</param>
/// <returns>A boolean indicating whether the number is prime or not.</returns>
public bool IsPrime(long numberToCheck) => primes[numberToCheck];
/// <summary>
/// Returns an IEnumerable of long primes in asending order.
/// </summary>
/// <returns>Primes in ascending order.</returns>
public IEnumerable<long> GetPrimes()
{
for(long i = 2; i < primes.Length; i++)
{
if (primes[i])
{
yield return i;
}
}
}
}