-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathLinearSieveOfEratosthenes.cs
More file actions
51 lines (42 loc) · 1.2 KB
/
LinearSieveOfEratosthenes.cs
File metadata and controls
51 lines (42 loc) · 1.2 KB
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
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;
}
}
}