Project Euler > Problem 87 > Prime power triples (Java Solution)

Problem:

The smallest number expressible as the sum of a prime square, prime cube, and prime fourth power is 28. In fact, there are exactly four numbers below fifty that can be expressed in such a way:

28 = 22 + 23 + 24
33 = 32 + 23 + 24
49 = 52 + 23 + 24
47 = 22 + 33 + 24

How many numbers below fifty million can be expressed as the sum of a prime square, prime cube, and prime fourth power?


Solution:

748317

Code:
The solution may include methods that will be found here: Library.java .

public interface EulerSolution{

public String run();

}
/* 
* Solution to Project Euler problem 37
* By Nayuki Minase
*
* http://nayuki.eigenstate.org/page/project-euler-solutions
* https://github.com/nayuki/Project-Euler-solutions
*/


public final class p037 implements EulerSolution {

public static void main(String[] args) {
System.out.println(new p037().run());
}


public String run() {
long sum = 0;
for (int count = 0, n = 10; count < 11; n++) {
if (isTruncatablePrime(n)) {
sum += n;
count++;
}
}
return Long.toString(sum);
}


private static boolean isTruncatablePrime(int n) {
// Test if left-truncatable
for (long i = 10; i <= n; i *= 10) {
if (!Library.isPrime(n % (int)i))
return false;
}

// Test if right-truncatable
for (; n != 0; n /= 10) {
if (!Library.isPrime(n))
return false;
}

return true;
}

}

No comments:

Post a Comment