Problem:
Looking at the table below, it is easy to verify that the maximum possible sum of adjacent numbers in any direction (horizontal, vertical, diagonal or anti-diagonal) is 16 (= 8 + 7 + 1).
[−]2 5 3 2
9 [−]6 5 1
3 2 7 3
[−]1 8 [−]4 8
Now, let us repeat the search, but on a much larger scale:
First, generate four million pseudo-random numbers using a specific form of what is known as a "Lagged Fibonacci Generator":
For 1 [≤] k [≤] 55, sk = [100003 [−] 200003k + 300007k3] (modulo 1000000) [−] 500000.
For 56 [≤] k [≤] 4000000, sk = [sk[−]24 + sk[−]55 + 1000000] (modulo 1000000) [−] 500000.
Thus, s10 = [−]393027 and s100 = 86613.
The terms of s are then arranged in a 2000[×]2000 table, using the first 2000 numbers to fill the first row (sequentially), the next 2000 numbers to fill the second row, and so on.
Finally, find the greatest sum of (any number of) adjacent entries in any direction (horizontal, vertical, diagonal or anti-diagonal).
[−]2 5 3 2
9 [−]6 5 1
3 2 7 3
[−]1 8 [−]4 8
Now, let us repeat the search, but on a much larger scale:
First, generate four million pseudo-random numbers using a specific form of what is known as a "Lagged Fibonacci Generator":
For 1 [≤] k [≤] 55, sk = [100003 [−] 200003k + 300007k3] (modulo 1000000) [−] 500000.
For 56 [≤] k [≤] 4000000, sk = [sk[−]24 + sk[−]55 + 1000000] (modulo 1000000) [−] 500000.
Thus, s10 = [−]393027 and s100 = 86613.
The terms of s are then arranged in a 2000[×]2000 table, using the first 2000 numbers to fill the first row (sequentially), the next 2000 numbers to fill the second row, and so on.
Finally, find the greatest sum of (any number of) adjacent entries in any direction (horizontal, vertical, diagonal or anti-diagonal).
Solution:
296962999629
Code:
The solution may include methods that will be found here: Library.java .
public interface EulerSolution{
public String run();
}
/*
* Solution to Project Euler problem 49
* By Nayuki Minase
*
* http://nayuki.eigenstate.org/page/project-euler-solutions
* https://github.com/nayuki/Project-Euler-solutions
*/
import java.util.Arrays;
public final class p049 implements EulerSolution {
public static void main(String[] args) {
System.out.println(new p049().run());
}
private static final int LIMIT = 10000;
public String run() {
boolean[] isPrime = Library.listPrimality(LIMIT - 1);
for (int base = 1000; base < LIMIT; base++) {
if (isPrime[base]) {
for (int step = 1; step < LIMIT; step++) {
int a = base + step;
int b = a + step;
if ( a < LIMIT && isPrime[a] && hasSameDigits(a, base)
&& b < LIMIT && isPrime[b] && hasSameDigits(b, base)
&& (base != 1487 || a != 4817))
return "" + base + a + b;
}
}
}
throw new RuntimeException("Not found");
}
private static boolean hasSameDigits(int x, int y) {
char[] xdigits = Integer.toString(x).toCharArray();
char[] ydigits = Integer.toString(y).toCharArray();
Arrays.sort(xdigits);
Arrays.sort(ydigits);
return Arrays.equals(xdigits, ydigits);
}
}
No comments :
Post a Comment