-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathid0051.c
130 lines (100 loc) · 2.55 KB
/
id0051.c
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
// Licensed under the MIT License.
// Prime Digit Replacements
#include "../lib/euler.h"
#include "../lib/hash.h"
#include "../lib/sieve_iterator.h"
#include "../lib/string_builder.h"
static bool mask_list_mask(StringBuilder value)
{
int counts[10] = { 0 };
for (size_t i = 0; i < value->length; i++)
{
counts[value->buffer[i] - '0']++;
}
for (int i = 0; i <= 2; i++)
{
if (counts[i] < 2)
{
continue;
}
for (size_t j = 0; j < value->length; j++)
{
if (value->buffer[j] - '0' == i)
{
value->buffer[j] = '*';
}
}
return true;
}
return false;
}
static long math_prime_digit_replacement(
Sieve primes,
StringBuilder mask,
StringBuilder image)
{
struct SieveIterator it;
for (sieve_begin(&it, primes); ; sieve_next(&it))
{
string_builder_clear(mask);
euler_ok(string_builder_append_format(mask, "%lld", it.current));
if (!mask_list_mask(mask))
{
continue;
}
long result = 0;
long length = 0;
for (int i = 0; i < 10; i++)
{
string_builder_clear(image);
for (size_t j = 0; j < mask->length; j++)
{
char c;
if (mask->buffer[j] == '*')
{
c = i + '0';
}
else
{
c = mask->buffer[j];
}
euler_ok(string_builder_append_char(image, c));
}
long n = atol(image->buffer);
if (n <= 100000)
{
continue;
}
Primality test = sieve_test(primes, n, miller_rabin_primality_test);
if (test != PRIMALITY_PRIME)
{
continue;
}
if (!length)
{
result = n;
}
length++;
}
if (length == 8)
{
return result;
}
}
return -1;
}
int main(void)
{
struct Sieve primes;
struct StringBuilder mask;
struct StringBuilder image;
clock_t start = clock();
euler_ok(sieve(&primes, 0));
euler_ok(string_builder(&mask, 0));
euler_ok(string_builder(&image, 0));
long first = math_prime_digit_replacement(&primes, &mask, &image);
finalize_sieve(&primes);
finalize_string_builder(&mask);
finalize_string_builder(&image);
return euler_submit(51, first, start);
}