-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path10.cs
60 lines (50 loc) · 1.47 KB
/
10.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
/* The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
*
* Find the sum of all the primes below two million.
*/
using System;
using System.Linq;
/* Compile: mcs 10.cs
* Run: mono 10.exe
*/
namespace Ten
{
class TenSolution {
static void Main(string[] args)
{
bool[] primeBools = EulerSieve(2_000_000);
long sum = 2; // primeBools starts at 3
for (int i = 0; i < primeBools.Length; i++) {
if (primeBools[i]) {
sum += FromIdx(i);
}
}
Console.WriteLine(sum);
}
private static bool[] EulerSieve(int limit)
{
int limitIdx = ToIdx(limit);
bool[] odds = Enumerable.Repeat(true, limitIdx + 1).ToArray();
int lastIdxCheck = ToIdx(Convert.ToInt32(Math.Sqrt(limit)));
for (int i = 0; i <= lastIdxCheck; i += 1)
{
int iValue = FromIdx(i);
for (int j = 0; iValue * FromIdx(i + j) < limit; j += 1)
{
odds[ToIdx(iValue * (FromIdx(i + j)))] = false;
}
}
return odds;
}
/** 3 -> 0, 5 -> 1, and so on. */
private static int ToIdx(int n)
{
return ((n - 1) / 2) - 1;
}
/** 0 -> 3, 1 -> 5, and so on. */
private static int FromIdx(int i)
{
return ((i + 1) * 2) + 1;
}
}
}