Problem:
The arithmetic sequence, 1487, 4817, 8147, in which each of the terms increases by 3330, is unusual in two ways: (i) each of the three terms are prime, and, (ii) each of the 4-digit numbers are permutations of one another.
There are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes, exhibiting this property, but there is one other 4-digit increasing sequence.
What 12-digit number do you form by concatenating the three terms in this sequence?
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