chore(CSharp): Added Sieve of Eratosthenes to generate primes from 1 to N (#502)
parent
20a485a42c
commit
022bd22af0
|
@ -6,6 +6,7 @@ For running the `.cs` file please using [.Net Finddle](https://dotnetfiddle.net/
|
|||
|
||||
## Number Theory
|
||||
1. [Big Mod Algorithm](src/Number-Theory/big-mod.cs)
|
||||
2. [Sieve of Eratosthenes](src/Number-Theory/sieve-of-eratosthenes.cs)
|
||||
|
||||
## Sorts
|
||||
|
||||
|
|
|
@ -0,0 +1,46 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace Algorithms.NumberTheory
|
||||
{
|
||||
public class SieveOfEratosthenes
|
||||
{
|
||||
// returns all the prime numbers from 1 to max
|
||||
public static List<int> PrimeGenerator(int max)
|
||||
{
|
||||
List<bool> isPrime = Enumerable.Repeat(true, max + 1).ToList();
|
||||
|
||||
isPrime[0] = isPrime[1] = false;
|
||||
for(int i = 4; i <= max; i += 2)
|
||||
{
|
||||
isPrime[i] = false;
|
||||
}
|
||||
|
||||
int squareRoot = (int)Math.Sqrt(max);
|
||||
for(int i = 3; i <= squareRoot; i += 2)
|
||||
{
|
||||
if(isPrime[i])
|
||||
{
|
||||
for(int j = 2 * i; j <= max; j += i)
|
||||
{
|
||||
isPrime[j] = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
List<int> primeNumbers = isPrime.Select((value, index) => new { value, index })
|
||||
.Where(obj => obj.value == true)
|
||||
.Select(obj => obj.index)
|
||||
.ToList();
|
||||
|
||||
return primeNumbers;
|
||||
}
|
||||
|
||||
public static void Main()
|
||||
{
|
||||
List<int> primeNumbers = PrimeGenerator(100);
|
||||
Console.WriteLine(string.Join(", ", primeNumbers));
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
using NUnit.Framework;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Algorithms.Tests.NumberTheory
|
||||
{
|
||||
[TestFixture]
|
||||
public class SieveOfEratosthenes
|
||||
{
|
||||
[TestCase(100, "2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97")]
|
||||
public void SieveOfEratosthenes_ShouldReturnExpected(int max, string expected)
|
||||
{
|
||||
List<int> primeNumbers = Algorithms.NumberTheory.SieveOfEratosthenes.PrimeGenerator(max);
|
||||
Assert.AreEqual(expected, string.Join(", ", primeNumbers));
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue