Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Linear Sieve Algorithm #143

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions Algorithms/Numeric/LinearSieveOfEratosthenes.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

/***
* Generates all prime numbers up to a given number
* Wikipedia: http://e-maxx.ru/algo/prime_sieve_linear
*/


namespace Algorithms.Numeric
{
public static class LinearSieveOfEratosthenes
{
/// <summary>
/// Calculate primes up to a given number
/// Time Complexity: O(N)
/// Memory: O(N)
/// </summary>
public static List<int> GeneratePrimesUpTo(int N)
{
//if N is negative, we should return empty list of primes
if (N < 0) return new List<int>();


int[] lp=new int[N+1];

//List of primes
var pr = new List<int>();

int op = 0;
for (int i = 2; i <= N; ++i)
{
if (lp[i] == 0)
{
lp[i] = i;
pr.Add(i);
}
for (int j = 0; j < pr.Count && pr[j] <= lp[i] && i * pr[j] <= N; ++j)
{
lp[i * pr[j]] = pr[j];
op++;
}
}

return pr;
}

}
}
46 changes: 46 additions & 0 deletions UnitTest/AlgorithmsTests/LinearSieveOfEratosthenesTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
using Algorithms.Numeric;
using System.Linq;
using Xunit;
using Xunit.Abstractions;

using System.Diagnostics;
namespace UnitTest.AlgorithmsTests
{
public class LinearSieveOfEratosthenesTests
{
private readonly ITestOutputHelper _testOutputHelper;
public LinearSieveOfEratosthenesTests(ITestOutputHelper testOutputHelper)
{
_testOutputHelper = testOutputHelper;
}
private const int MaxNumber = 100;

[Fact]
public void DoTests()
{
var results = LinearSieveOfEratosthenes.GeneratePrimesUpTo(MaxNumber);
Assert.NotNull(results);
Assert.True(results.Any());
Assert.Equal(results.Count(), 25);
Assert.DoesNotContain(1, results);
Assert.Contains(2, results);
Assert.Contains(7, results);
Assert.Contains(23, results);
Assert.Contains(41, results);
Assert.Contains(97, results);

}

[Fact]
public void TestsForEmpty()
{
var results = LinearSieveOfEratosthenes.GeneratePrimesUpTo(0);
Assert.NotNull(results);
Assert.False(results.Any());

var results2 = LinearSieveOfEratosthenes.GeneratePrimesUpTo(-100);
Assert.NotNull(results2);
Assert.False(results2.Any());
}
}
}