-
Notifications
You must be signed in to change notification settings - Fork 0
/
e87.d
109 lines (104 loc) · 2.53 KB
/
e87.d
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
import std.stdio;
import std.math;
import std.conv;
/** Writing all the casts is annoying */
int isqrt(int x) {
return to!int(floor(sqrt(to!float(x))));
}
/** "Basic" Prime Sieve */
int[] sieve(int bound) {
int[] partial;
int rbound = isqrt(bound);
if (bound < 11) {
return [2, 3, 5, 7];
} else {
partial = sieve(rbound);
}
int current = rbound;
if (current % 2 == 0) {
current += 1;
}
int[] newprimes = partial;
while (current < bound) {
bool isprime = true;
int rcurrent = isqrt(current);
foreach (p; partial) {
if (p > rcurrent) {
break;
}
if (current % p == 0) {
isprime = false;
break;
}
}
if (isprime) {
newprimes ~= current;
}
current += 2;
}
return newprimes;
}
int BOUND = 50000000;
/**Set implemented with array of bits
Not only done for space efficiency, D does not
allow static arrays with 50000000 elements (at least by default).
*/
uint[50000000/32 + 1] is23sum;
void setIsSum(int elem) {
if (!isSum(elem)) {
is23sum[elem / 32] += 1 << (elem % 32);
}
}
bool isSum(int elem) {
return ((is23sum[elem / 32] >> (elem % 32)) & 1) > 0;
}
void main() {
// Get all necessary primes
int[] primes = sieve(isqrt(BOUND));
// Precompute arrays
int[] primes2;
foreach (p ; primes ) {
primes2 ~= pow(p , 2);
}
int[] primes3;
foreach (p ; primes ) {
int temp = pow(p, 3);
if (temp > BOUND) {
break;
} else {
primes3 ~= temp;
}
}
int[] primes4;
foreach (p; primes) {
int temp = pow(p, 4);
if (temp > BOUND) {
break;
} else {
primes4 ~= temp;
}
}
is23sum[] = 0;
// Precompute all numbers that are sums of squares and cubes
foreach (p2; primes2) {
foreach (p3; primes3) {
int s = p2 + p3;
if (s < BOUND) {
setIsSum(s);
}
}
}
int ans = 0;
// Checking for sum of square, cube, and 4th power
foreach(i; 27 .. BOUND) {
foreach (p4; primes4) {
if ( (i - p4) < 12) {
break;
} else if (isSum(i - p4)) {
ans = ans + 1;
break;
}
}
}
writeln(ans);
}