-
Notifications
You must be signed in to change notification settings - Fork 2
/
134.cs
145 lines (117 loc) · 3.73 KB
/
134.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
namespace euler
{
class Problem134
{
public static void Main(string[] args)
{
new Problem134().Bruteforce();
}
public void Bruteforce()
{
Stopwatch clock = Stopwatch.StartNew();
int limit = 1000000;
int[] primes = Sieve(5, limit + 100);
long result = 0;
int i = 0;
while (primes[i] <= limit)
{
//solve the linear congruence
// 10^d(p1)*x + p1 == 0 (mod p2)
// 10^d(p1)*x == -p1 (mod p2)
// 10^d(p1)*x == p2-p1 (mod p2)
// ax == b mod n
long p1 = primes[i];
long p2 = primes[i + 1];
long a = DigitCountFactor(p1);
long b = p2 - p1;
long n = p2;
long[] rs = extended_gcd(a, n);
long x = rs[0] * b % n;
if (x < 0)
x = n + x;
result += x * a + p1;
i++;
}
clock.Stop();
Console.WriteLine("Sum of S: {0}", result);
Console.WriteLine("Solution took {0} ms", clock.Elapsed.TotalMilliseconds);
}
private long DigitCountFactor(long number)
{
long factor = 1;
while (number > 0)
{
factor *= 10;
number /= 10;
}
return factor;
}
private long[] extended_gcd(long a, long b)
{
long x = 0;
long lastx = 1;
long y = 1;
long lasty = 0;
while (b != 0)
{
long quotient = a / b;
long temp = b;
b = a % b;
a = temp;
temp = x;
x = lastx - quotient * x;
lastx = temp;
temp = y;
y = lasty - quotient * y;
lasty = temp;
}
return new long[] { lastx, lasty, a };
}
/// <summary>
/// Returns an array of primes up to upperLimit.
/// </summary>
/// <remarks>Efficient Sieve of Eratosthenes.</remarks>
public static int[] Sieve(int lowerLimit, int upperLimit)
{
if (lowerLimit > upperLimit)
{
return new int[0];
}
upperLimit = Math.Max(upperLimit, 1);
int sieveBound = (int)(upperLimit - 1) / 2;
int upperSqrt = ((int)Math.Sqrt(upperLimit) - 1) / 2;
BitArray isPrime = new BitArray(sieveBound + 1, true);
for (int i = 1, ii = 3, iii = 4; i <= upperSqrt; i++, ii += 2, iii += 4 * i)
{
if (isPrime.Get(i))
{
for (int j = iii; j <= sieveBound; j += ii)
{
isPrime.Set(j, false);
}
}
}
List<int> primes = new List<int>(Math.Max(Math.Min((int)(upperLimit / (Math.Log(upperLimit) - 1.08366)), upperLimit), 10));
if (lowerLimit < 3 && upperLimit >= 2)
{
primes.Add(2);
}
if (lowerLimit < 3)
{
lowerLimit = 3;
}
for (int i = lowerLimit / 2, ii = 2 * i + 1; i <= sieveBound; i++, ii += 2)
{
if (isPrime.Get(i))
{
primes.Add(ii);
}
}
return primes.ToArray();
}
}
}