forked from nayuki/Project-Euler-solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Library.java
401 lines (330 loc) · 10 KB
/
Library.java
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
/*
* Shared code for solutions to Project Euler problems
* By Nayuki Minase
*
* http://nayuki.eigenstate.org/page/project-euler-solutions
* https://github.com/nayuki/Project-Euler-solutions
*/
import java.math.BigInteger;
final class Library {
// Returns the reverse of the given string.
public static String reverse(String s) {
return new StringBuilder(s).reverse().toString();
}
// Tests whether the given string is a palindrome.
public static boolean isPalindrome(String s) {
return s.equals(reverse(s));
}
// Tests whether the given integer is a palindrome in decimal.
public static boolean isPalindrome(int x) {
return isPalindrome(Integer.toString(x));
}
// Returns floor(sqrt(x)).
public static int sqrt(int x) {
if (x < 0)
throw new IllegalArgumentException("Square root of negative number");
int y = 0;
for (int i = 32768; i != 0; i >>>= 1) {
y |= i;
if (y > 46340 || y * y > x)
y ^= i;
}
return y;
}
// Returns floor(sqrt(x)).
public static long sqrt(long x) {
if (x < 0)
throw new IllegalArgumentException("Square root of negative number");
long y = 0;
for (long i = 1L << 31; i != 0; i >>>= 1) {
y |= i;
if (y > 3037000499L || y * y > x)
y ^= i;
}
return y;
}
// Tests whether x is a perfect square.
public static boolean isSquare(int x) {
if (x < 0)
return false;
int sqrt = Library.sqrt(x);
return sqrt * sqrt == x;
}
// Returns x to the power of y.
public static int pow(int x, int y) {
if (y < 0)
throw new IllegalArgumentException("Negative exponent");
int z = 1;
for (int i = 0; i < y; i++) {
if (Integer.MAX_VALUE / z < x)
throw new ArithmeticException("Overflow");
z *= x;
}
return z;
}
// Returns x^y mod m.
public static int powMod(int x, int y, int m) {
if (x < 0)
throw new IllegalArgumentException("Negative base not handled");
if (y < 0)
throw new IllegalArgumentException("Reciprocal not handled");
if (m <= 0)
throw new IllegalArgumentException("Invalid modulus");
// Exponentiation by squaring
int z = 1;
while (y != 0) {
if ((y & 1) != 0)
z = (int)((long)z * x % m);
x = (int)((long)x * x % m);
y >>>= 1;
}
return z;
}
// Returns x^-1 mod m. Note that x * x^-1 mod m = x^-1 * x mod m = 1.
public static int reciprocalMod(int x, int m) {
if (m < 0 || x < 0 || x >= m)
throw new IllegalArgumentException();
// Based on a simplification of the extended Euclidean algorithm
int y = x;
x = m;
int a = 0;
int b = 1;
while (y != 0) {
int z = x % y;
int c = a - x / y * b;
x = y;
y = z;
a = b;
b = c;
}
if (x == 1)
return (a + m) % m;
else
throw new IllegalArgumentException("Reciprocal does not exist");
}
// Returns n!.
public static BigInteger factorial(int n) {
if (n < 0)
throw new IllegalArgumentException("Factorial of negative number");
BigInteger prod = BigInteger.ONE;
for (int i = 2; i <= n; i++)
prod = prod.multiply(BigInteger.valueOf(i));
return prod;
}
// Returns n choose k.
public static BigInteger binomial(int n, int k) {
return factorial(n).divide(factorial(n - k).multiply(factorial(k)));
}
// Returns the largest non-negative integer that divides both x and y.
public static int gcd(int x, int y) {
while (y != 0) {
int z = x % y;
x = y;
y = z;
}
return x;
}
// Tests whether the given integer is prime.
public static boolean isPrime(int x) {
if (x < 0)
throw new IllegalArgumentException("Negative number");
if (x == 0 || x == 1)
return false;
else if (x == 2)
return true;
else {
if (x % 2 == 0)
return false;
for (int i = 3, end = sqrt(x); i <= end; i += 2) {
if (x % i == 0)
return false;
}
return true;
}
}
// Returns a Boolean array 'isPrime' where isPrime[i] indicates whether i is prime, for 0 <= i <= n.
// For a large batch of queries, this is faster than calling isPrime() for each integer.
// For example: listPrimality(100) = {false, false, true, true, false, true, false, true, false, false, ...}.
public static boolean[] listPrimality(int n) {
if (n < 0)
throw new IllegalArgumentException("Negative size");
boolean[] prime = new boolean[n + 1];
if (n >= 2)
prime[2] = true;
for (int i = 3; i <= n; i += 2)
prime[i] = true;
// Sieve of Eratosthenes
for (int i = 3, end = sqrt(n); i <= end; i += 2) {
if (prime[i]) {
for (int j = i * i; j <= n; j += i << 1)
prime[j] = false;
}
}
return prime;
}
// Returns all the prime numbers less than or equal to n, in ascending order.
// For example: listPrimes(100) = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, ..., 83, 89, 97}.
public static int[] listPrimes(int n) {
if (n < 0)
throw new IllegalArgumentException("Negative size");
boolean[] isPrime = listPrimality(n);
int count = 0;
for (boolean b : isPrime) {
if (b)
count++;
}
int[] primes = new int[count];
for (int i = 0, j = 0; i < isPrime.length; i++) {
if (isPrime[i]) {
primes[j] = i;
j++;
}
}
return primes;
}
// Returns an array spf where spf[k] is the smallest prime factor of k, valid for 0 <= k <= n.
// For example: listSmallestPrimeFactors(10) = {0, 0, 2, 3, 2, 5, 2, 7, 2, 3, 2}.
public static int[] listSmallestPrimeFactors(int n) {
int[] result = new int[n + 1];
for (int i = 2; i < result.length; i++) {
if (result[i] == 0) {
result[i] = i;
if ((long)i * i <= n) {
for (int j = i * i; j <= n; j += i) {
if (result[j] == 0)
result[j] = i;
}
}
}
}
return result;
}
// Returns the number of integers in the range [1, n] that are coprime with n.
// For example, totient(12) = 4 because these integers are coprime with 12: 1, 5, 7, 11.
public static int totient(int n) {
if (n <= 0)
throw new IllegalArgumentException("Totient of non-positive integer");
int p = 1;
for (int i = 2, end = Library.sqrt(n); i <= end; i++) { // Trial division
if (n % i == 0) { // Found a factor
p *= i - 1;
n /= i;
while (n % i == 0) {
p *= i;
n /= i;
}
end = Library.sqrt(n);
}
}
if (n != 1)
p *= n - 1;
return p;
}
// Returns an array 'totients' where totients[i] == totient(i), for 0 <= i <= n.
// For a large batch of queries, this is faster than calling totient() for each integer.
public static int[] listTotients(int n) {
if (n < 0)
throw new IllegalArgumentException("Negative size");
int[] totients = new int[n + 1];
for (int i = 0; i <= n; i++)
totients[i] = i;
for (int i = 2; i <= n; i++) {
if (totients[i] == i) { // i is prime
for (int j = i; j <= n; j += i)
totients[j] = totients[j] / i * (i - 1);
}
}
return totients;
}
// Returns the same result as x.multiply(y), but is faster for large integers.
public static BigInteger multiply(BigInteger x, BigInteger y) {
final int CUTOFF = 1536;
if (x.bitLength() <= CUTOFF || y.bitLength() <= CUTOFF) { // Base case
return x.multiply(y);
} else { // Karatsuba fast multiplication
int n = Math.max(x.bitLength(), y.bitLength());
int half = (n + 32) / 64 * 32;
BigInteger mask = BigInteger.ONE.shiftLeft(half).subtract(BigInteger.ONE);
BigInteger xlow = x.and(mask);
BigInteger ylow = y.and(mask);
BigInteger xhigh = x.shiftRight(half);
BigInteger yhigh = y.shiftRight(half);
BigInteger a = multiply(xhigh, yhigh);
BigInteger b = multiply(xlow.add(xhigh), ylow.add(yhigh));
BigInteger c = multiply(xlow, ylow);
BigInteger d = b.subtract(a).subtract(c);
return a.shiftLeft(half).add(d).shiftLeft(half).add(c);
}
}
// Advances the given sequence to the next permutation and returns whether a permutation was performed.
// If no permutation was performed, then the input state was already the last possible permutation (a non-ascending sequence).
// For example:
// - nextPermutation({0,0,1}) changes the argument array to {0,1,0} and returns true.
// - nextPermutation({1,0,0}) leaves the argument array unchanged and returns false.
public static boolean nextPermutation(int[] a) {
int i, n = a.length;
for (i = n - 2; ; i--) {
if (i < 0)
return false;
if (a[i] < a[i + 1])
break;
}
for (int j = 1; i + j < n - j; j++) {
int tp = a[i + j];
a[i + j] = a[n - j];
a[n - j] = tp;
}
int j;
for (j = i + 1; a[j] <= a[i]; j++);
int tp = a[i];
a[i] = a[j];
a[j] = tp;
return true;
}
}
// Immutable unlimited precision fraction
final class Fraction {
public final BigInteger numerator; // Always coprime with denominator
public final BigInteger denominator; // Always positive
public Fraction(BigInteger numer, BigInteger denom) {
if (denom.signum() == 0)
throw new ArithmeticException("Division by zero");
// Reduce to canonical form
if (denom.signum() == -1) {
numer = numer.negate();
denom = denom.negate();
}
BigInteger gcd = numer.gcd(denom);
if (!gcd.equals(BigInteger.ONE)) {
numer = numer.divide(gcd);
denom = denom.divide(gcd);
}
numerator = numer;
denominator = denom;
}
public Fraction add(Fraction other) {
return new Fraction(numerator.multiply(other.denominator).add(other.numerator.multiply(denominator)), denominator.multiply(other.denominator));
}
public Fraction subtract(Fraction other) {
return new Fraction(numerator.multiply(other.denominator).subtract(other.numerator.multiply(denominator)), denominator.multiply(other.denominator));
}
public Fraction multiply(Fraction other) {
return new Fraction(numerator.multiply(other.numerator), denominator.multiply(other.denominator));
}
public Fraction divide(Fraction other) {
return new Fraction(numerator.multiply(other.denominator), denominator.multiply(other.numerator));
}
public boolean equals(Object obj) {
if (obj instanceof Fraction) {
Fraction other = (Fraction)obj;
return numerator.equals(other.numerator) && denominator.equals(other.denominator);
} else
return false;
}
public int hashCode() {
return numerator.hashCode() + denominator.hashCode();
}
public String toString() {
return numerator + "/" + denominator;
}
}