-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
77 lines (67 loc) · 1.73 KB
/
Program.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
68
69
70
71
72
73
74
75
76
77
const int PRIMES_UP_TO = 30;
var primes = new List<int>();
var pool = new Pool();
primes.Add(2);
pool.Insert(2);
for (int number = 3; number < PRIMES_UP_TO; number++)
{
var smallestMultiplier = pool.GetSmallestMultiplier();
if (smallestMultiplier > 0)
{
if (number < smallestMultiplier)
{
primes.Add(number);
pool.Insert(number);
}
else
{
pool.Update(number);
}
}
}
readonly struct Pool
{
private readonly List<(int Prime, int Multiple)> pairs;
public Pool()
{
pairs = new();
}
public readonly void Insert(int value)
=>
this.pairs.Add((value, value * value));
public readonly int GetSmallestMultiplier()
=>
this.pairs.Count > 0
? this.pairs[0].Multiple
: 0;
public void Update(int value)
{
int index = 0;
for (; index < pairs.Count; index++)
{
if (pairs[index].Multiple == value)
{
pairs[index] = (pairs[index].Prime, pairs[index].Multiple + pairs[index].Prime);
}
else
{
break;
}
}
if (this.pairs.Count > 1)
{
while (index >= 0)
{
index -= 1;
int i = index;
while (this.pairs[i].Multiple > this.pairs[i + 1].Multiple)
{
(this.pairs[i + 1], this.pairs[i]) = (this.pairs[i], this.pairs[i + 1]);
i += 1;
}
if (index == 0)
break;
}
}
}
}